公司需求后臺(tái)定位,間隔五分鐘后臺(tái)上傳坐標(biāo)信息,這里主要把后臺(tái)定位功能整理了一下。
plist 的權(quán)限設(shè)置 這里就不具體說了。
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()
}
//定位代理函數(shù)
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("經(jīng)度\(mostRecentLocation.coordinate.latitude)")
print("緯度\(mostRecentLocation.coordinate.longitude)")
}
}
最后就是關(guān)于后臺(tái)定位審核問題,如果只是把定位數(shù)據(jù)傳給后臺(tái)是會(huì)被蘋果拒絕的,需要把定位得坐標(biāo)展現(xiàn)在地圖上,或者用個(gè)tableview把定位得信息列出來。