[英]App location in background on iOS 8
我想在應用程序背景中獲取用戶的位置。 如果我使用9秒或更短秒的計時器,它工作正常。 如果我使用10秒甚至更長時間,我無法獲得用戶的位置...
我的AppDelegate.swift
:
import UIKit
import CoreLocation
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, CLLocationManagerDelegate {
var window: UIWindow?
var backgroundTaskIdentifier: UIBackgroundTaskIdentifier = UIBackgroundTaskInvalid
var myTimer: NSTimer?
var locationManager = CLLocationManager()
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func isMultitaskingSupported() -> Bool {
return UIDevice.currentDevice().multitaskingSupported
}
func timerMethod(sender: NSTimer) {
let backgroundTimerRemainig = UIApplication.sharedApplication().backgroundTimeRemaining
self.locationManager.startUpdatingLocation()
if backgroundTimerRemainig == DBL_MAX {
println("test1")
} else {
println("test")
self.locationManager.delegate = self
self.locationManager.startUpdatingLocation()
}
}
func applicationWillResignActive(application: UIApplication) {
}
func applicationDidEnterBackground(application: UIApplication){
if !isMultitaskingSupported() {
return
}
myTimer = NSTimer.scheduledTimerWithTimeInterval(60.0,
target: self,
selector: "timerMethod:",
userInfo: nil,
repeats: true)
backgroundTaskIdentifier = UIApplication.sharedApplication().beginBackgroundTaskWithExpirationHandler {
() -> Void in
UIApplication.sharedApplication().endBackgroundTask(self.backgroundTaskIdentifier)
}
}
func endBackgroundTask() {
let mainQueue = dispatch_get_main_queue()
dispatch_async(mainQueue) {
[weak self] in
if let timer = self!.myTimer {
timer.invalidate()
self!.myTimer = nil
UIApplication.sharedApplication().endBackgroundTask(self!.backgroundTaskIdentifier)
self!.backgroundTaskIdentifier = UIBackgroundTaskInvalid
}
}
}
func applicationWillEnterForeground(application: UIApplication) {
if backgroundTaskIdentifier != UIBackgroundTaskInvalid {
endBackgroundTask()
}
}
func applicationDidBecomeActive(application: UIApplication) {
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
func locationManager(manager: CLLocationManager!, didUpdateToLocation locations: [AnyObject]) {
var latValue = locationManager.location.coordinate.latitude
var lonValue = locationManager.location.coordinate.longitude
}
}
當我使用10秒甚至更長時間時,為什么我無法獲得用戶的位置?
因為大約在調用didEnterBackground
10秒后應用程序被暫停 。
該應用程序在后台,但沒有執行代碼。 系統會自動將應用程序移動到此狀態,並且在執行此操作之前不會通知它們。 暫停時,應用程序仍保留在內存中,但不執行任何代碼。
這是iOS應用程序生命周期 。
如果您想在后台獲取位置更新,您有兩種選擇:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.