我有一个包含计时器功能的 iOS 应用程序。应用程序在前台运行时完全正常,计时器运行良好。但是当我进入后台模式时,计时器仅工作 30 秒,并且出现“不存在标识符错误的后台任务”。我的应用程序中启用了后台模式和后台处理功能有解决方案吗?
**:SOLUTION WORKING:**
On Location Updates in Background Modes from capabilities
Put below code in your viewcontroller where timer is running
var locationManager = CLLocationManager()
CLLocationManagerDelegate
if (CLLocationManager.locationServicesEnabled())
{
self.locationManager = CLLocationManager()
self.locationManager.delegate = self
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
self.locationManager.requestAlwaysAuthorization()
self.locationManager.startUpdatingLocation()
self.locationManager.allowsBackgroundLocationUpdates = true
self.locationManager.pausesLocationUpdatesAutomatically = false
}
backgroundTaskIdentifier = UIApplication.shared.beginBackgroundTask(expirationHandler: {
UIApplication.shared.endBackgroundTask(self.backgroundTaskIdentifier!)
})
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location = locations.last! as CLLocation
let center = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)
_ = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))
}