iOS background mode location update - manager doesn't update in background mode

萝らか妹 提交于 2019-12-12 17:34:20

问题


I just followed http://www.raywenderlich.com/92428/background-modes-ios-swift-tutorial location update part.

But manager doesn't print location info in background mode.

Then manager print logs to Xcode's console when app enter foreground.

Is this code right?

import UIKit
import CoreLocation

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, CLLocationManagerDelegate {

var window: UIWindow?
var manager = CLLocationManager()


func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    // Override point for customization after application launch.

    manager.desiredAccuracy = kCLLocationAccuracyBest
    manager.delegate = self
    manager.requestAlwaysAuthorization()
    manager.startUpdatingLocation()

    return true
}

func locationManager(manager: CLLocationManager, didUpdateToLocation newLocation: CLLocation, fromLocation oldLocation: CLLocation) {
    if UIApplication.sharedApplication().applicationState != .Active {
        NSLog("App is backgrounded. New location is %@", newLocation)
    }
}
.....

}

回答1:


I got answer for myself.

If your app running on iOS 9.0 or above and want to run your location service app on background,

you have to allowsBackgroundLocationUpdates variable set to true.

so here is my code.

import UIKit
import CoreLocation

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, CLLocationManagerDelegate {

var window: UIWindow?
var manager = CLLocationManager()


func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    // Override point for customization after application launch.

    manager.desiredAccuracy = kCLLocationAccuracyBest
    manager.delegate = self
    manager.requestAlwaysAuthorization()
    manager.startUpdatingLocation()
    if #available(iOS 9.0, *){
        manager.allowsBackgroundLocationUpdates = true
    }   

    return true
}

func locationManager(manager: CLLocationManager, didUpdateToLocation newLocation: CLLocation, fromLocation oldLocation: CLLocation) {
    if UIApplication.sharedApplication().applicationState != .Active {
        NSLog("App is backgrounded. New location is %@", newLocation)
    }
}
.....

}


来源:https://stackoverflow.com/questions/33385652/ios-background-mode-location-update-manager-doesnt-update-in-background-mode

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!