swift3.0 后台定位功能

公司需求后台定位,间隔五分钟后台上传坐标信息,这里主要把后台定位功能整理了一下。
plist 的权限设置 这里就不具体说了。

import UIKit
import CoreLocation
class LocationUpdateManager: NSObject, CLLocationManagerDelegate{
    
    var standardlocationManager:CLLocationManager?
    
    var lastTimestamp:NSDate?
    
    var timer: Timer?
    
    static let sharedStandardInstance = LocationUpdateManager()
    
    private override init() {
        super.init()
        self.standardlocationManager = CLLocationManager()
        self.standardlocationManager?.delegate = self
        self.standardlocationManager?.desiredAccuracy = kCLLocationAccuracyBest
        self.standardlocationManager?.distanceFilter = 100
        self.standardlocationManager?.pausesLocationUpdatesAutomatically = false
        
        if #available(iOS 8.0, *) {
            self.standardlocationManager?.requestAlwaysAuthorization()
        }
        
        if #available(iOS 9.0, *) {
            self.standardlocationManager?.allowsBackgroundLocationUpdates = true
        }
        
    }
    
    func startStandardUpdatingLocation()  {
        self.standardlocationManager?.startUpdatingLocation()
    }
    
    func stopStandardUpdatingLocation(){
        self.standardlocationManager?.stopUpdatingLocation()
    }
    
    //定位代理函数
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        let mostRecentLocation = locations.last
        if timer == nil {
            timer = Timer(fireAt: Date(), interval: 10, target: self, selector: #selector(self.printCurrentTime), userInfo: mostRecentLocation, repeats: true)
            RunLoop.current.add(timer!, forMode: .defaultRunLoopMode)
        }
    }
    func printCurrentTime() {
        
        let mostRecentLocation = timer?.userInfo as! CLLocation
        
        print("经度\(mostRecentLocation.coordinate.latitude)")
        print("纬度\(mostRecentLocation.coordinate.longitude)")
        
    }

}

最后就是关于后台定位审核问题,如果只是把定位数据传给后台是会被苹果拒绝的,需要把定位得坐标展现在地图上,或者用个tableview把定位得信息列出来。

你可能感兴趣的:(swift3.0 后台定位功能)