问题
I am writing an iOS app that requires the device's GPS loction to be updated when a push notification is received.
I use a closure to get the current GPS location. This code runs perfectly when the app is in the foreground (Both "New remote notification" and "Got location" is printed to console), but when the app is in the background, only "New remote notification" (and no location error) is printed to console. As a result I don't have the GPS location of the device at this point, which is very important for my app's functionality.
Any help would be greatly appreciated. Thanks.
I have in my Info.plist file for 'Required background modes';
App registers for location updates
App downloads content from the network
App downloads content in response to push notifications
My app also has access to location at all times, including the background (successfully tested at other points in the code): NSLocationAlwaysUsageDescription is in the Info.plist file
In my AppDelegate file:
func application(application: UIApplication!, didReceiveRemoteNotification userInfo:NSDictionary!) {
println("New remote notification")
var notification:NSDictionary = userInfo as NSDictionary
var loc: LocationManager?
loc = LocationManager()
loc!.fetchWithCompletion {location, error in
// fetch location or an error
if let myloc = location {
var lat = myloc.coordinate.latitude as Double
var lon = myloc.coordinate.longitude as Double
println("Got location")
} else if let err = error {
println(err.localizedDescription)
}
loc = nil
}
}
回答1:
If app is not in foreground, make sure to ask for a little time to complete the request with beginBackgroundTaskWithExpirationHandler
and then call endBackgroundTask
when done.
For more information, see the Executing Finite Length Tasks in the Background Execution chapter of the App Programming Guide for iOS.
来源:https://stackoverflow.com/questions/28011364/swift-ios-closure-will-not-run-in-background-when-remote-notification-received