【发布时间】:2016-07-08 23:56:52
【问题描述】:
我编写了下面的代码,它有一个每分钟调用一个回调函数的计时器。当应用程序进入后台时,我启动了另一个调用相同回调方法的计时器,但后台计时器只工作了三分钟。
我了解 Apple 只允许后台任务执行三分钟。我的应用更像是一个跟踪应用,即使应用在后台,也会每分钟跟踪用户的位置,所以我需要实现这个功能。
得知要使用beginBackgroundTaskWithExpirationHandler,但不知道我的实现是否正确。
注意:我在 plist toApp 寄存器中有必需的后台模式以进行位置更新。
非常感谢任何有效的代码或链接。
override func viewDidLoad() {
super.viewDidLoad()
timeInMinutes = 1 * 60
self.locationManager.requestAlwaysAuthorization()
self.locationManager.requestWhenInUseAuthorization()
if CLLocationManager.locationServicesEnabled() {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
locationManager.startUpdatingLocation()
}
var timer = NSTimer.scheduledTimerWithTimeInterval( timeInMinutes, target: self, selector: "updateLocation", userInfo: nil, repeats: true)
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]){
let locValue:CLLocationCoordinate2D = manager.location!.coordinate
self.latitude = locValue.latitude
self.longitude = locValue.longitude
if UIApplication.sharedApplication().applicationState == .Active {
} else {
backgroundTaskIdentifier = UIApplication.sharedApplication().beginBackgroundTaskWithExpirationHandler({ () -> Void in
self.backgroundTimer.invalidate()
self.backgroundTimer = NSTimer.scheduledTimerWithTimeInterval( 60.0, target: self, selector: "updateLocation", userInfo: nil, repeats: true)
})
}
}
func updateLocation() {
txtlocationLabel.text = String(n)
self.n = self.n+1
var timeRemaining = UIApplication.sharedApplication().backgroundTimeRemaining
print(timeRemaining)
if timeRemaining > 60.0 {
self.GeoLogLocation(self.latitude,Longitude: self.longitude) {
results in
print("View Controller: \(results)")
self.CheckResult(String(results))
}
} else {
if timeRemaining == 0 {
UIApplication.sharedApplication().endBackgroundTask(backgroundTaskIdentifier)
}
backgroundTaskIdentifier2 = UIApplication.sharedApplication().beginBackgroundTaskWithExpirationHandler({ () -> Void in
self.backgroundTimer.invalidate()
self.backgroundTimer = NSTimer.scheduledTimerWithTimeInterval( 60.0, target: self, selector: "updateLocation", userInfo: nil, repeats: true)
})
}
}
【问题讨论】:
标签: ios iphone swift background core-location