2
votes

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
are you enabled your background modes on location updatesAnbu.Karthik
@Anbu.Karthik Yeah. I turned on In Capabilities Setting.danny ocean
are you registered in your plist App registers for location updatesAnbu.Karthik
@Anbu.Karthik Yes. I write down NSLocationAlwaysUsageDescription in plist. So I Allowed update location always.danny ocean
@Anbu.Karthik also add items to Required background modes in plistdanny ocean

1 Answers

9
votes

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)
    }
}
.....

}