公司需求后臺定位当窗,間隔五分鐘后臺上傳坐標(biāo)信息,這里主要把后臺定位功能整理了一下寸宵。
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)于后臺定位審核問題,如果只是把定位數(shù)據(jù)傳給后臺是會被蘋果拒絕的梯影,需要把定位得坐標(biāo)展現(xiàn)在地圖上巫员,或者用個tableview把定位得信息列出來。