iOS后台模式位置更新-管理器不在后台模式下更新 [英] iOS background mode location update - manager doesn't update in background mode

查看:164
本文介绍了iOS后台模式位置更新-管理器不在后台模式下更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚关注了 http://www.raywenderlich.com/92428/background-modes-ios-swift-tutorial 位置更新部分.

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.

然后,当应用程序进入前台时,经理将打印日志记录到Xcode的控制台中.

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

此代码正确吗?

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

}

推荐答案

我自己得到了答案.

如果您的应用在iOS 9.0或更高版本上运行,并且希望在后台运行您的位置服务应用,

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

您必须将BackgroundLocationUpdates变量设置为true.

you have to allowsBackgroundLocationUpdates variable set to true.

这是我的代码.

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

}

这篇关于iOS后台模式位置更新-管理器不在后台模式下更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆