Periodic iOS background location updates

前端 未结 9 1448
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-22 14:56

I\'m writing an application that requires background location updates with high accuracy and low frequency. The solution seems to be a background NSTimer t

9条回答
  •  天涯浪人
    2020-11-22 15:28

    After iOS 8 their are several changes in CoreLocation framework related background fetch and updations made by apple.

    1) Apple introduce the AlwaysAuthorization request for fetching the location update in the application.

    2) Apple introduce backgroundLocationupdates for fetching location from background in iOS.

    For fetching location in background you need to enable Location Update in Capabilities of Xcode.

    //
    //  ViewController.swift
    //  DemoStackLocation
    //
    //  Created by iOS Test User on 02/01/18.
    //  Copyright © 2018 iOS Test User. All rights reserved.
    //
    
    import UIKit
    import CoreLocation
    
    class ViewController: UIViewController {
    
        var locationManager: CLLocationManager = CLLocationManager()
        override func viewDidLoad() {
            super.viewDidLoad()
            startLocationManager()
        }
    
        override func didReceiveMemoryWarning() {
            super.didReceiveMemoryWarning()
            // Dispose of any resources that can be recreated.
        }
    
        internal func startLocationManager(){
            locationManager.requestAlwaysAuthorization()
            locationManager.desiredAccuracy = kCLLocationAccuracyBest
            locationManager.delegate = self
            locationManager.allowsBackgroundLocationUpdates = true
            locationManager.startUpdatingLocation()
        }
    
    }
    
    extension ViewController : CLLocationManagerDelegate {
    
        func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]){
            let location = locations[0] as CLLocation
            print(location.coordinate.latitude) // prints user's latitude
            print(location.coordinate.longitude) //will print user's longitude
            print(location.speed) //will print user's speed
        }
    
    }
    

提交回复
热议问题