当应用的“位置”和“后台应用刷新”权限发生变化时,会在后台收到通知

时间:2015-04-24 21:21:05

标签: ios cllocationmanager background-process nsnotificationcenter user-permissions

当应用权限更改时,是否有人知道系统是否可以在后台通知应用?我特别感兴趣的是在用户更改“位置”权限和“后台应用刷新”权限时收到通知。

到目前为止,我已经研究了这种回叫方法:

locationManager(manager: CLLocationManager!, didChangeAuthorizationStatus status: CLAuthorizationStatus)

但是,应用程序不会在后台得到通知。

我还尝试为此通知添加观察者:

UIApplicationBackgroundRefreshStatusDidChangeNotification

但我也无法让它发挥作用。

这是我的代码:

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {        
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "checkBackgroundPermission", name: UIApplicationBackgroundRefreshStatusDidChangeNotification, object: nil)

    locationManager = CLLocationManager()
    locationManager.delegate = self
    locationManager.pausesLocationUpdatesAutomatically = false

    if(locationManager.respondsToSelector("requestAlwaysAuthorization")) {
        locationManager.requestAlwaysAuthorization()
    }

    if launchOptions?[UIApplicationLaunchOptionsLocationKey] != nil {
        locationManager = CLLocationManager()
        locationManager.delegate = self
        locationManager.pausesLocationUpdatesAutomatically = false

        let prefs:NSUserDefaults = NSUserDefaults.standardUserDefaults()
        let uuidString = prefs.stringForKey("UUID") as String!
        let uuid : NSUUID? = NSUUID(UUIDString: uuidString as String)

        beaconRegionGeneral = CLBeaconRegion(proximityUUID: NSUUID(UUIDString: uuidString), identifier: "general")

        locationManager.startRangingBeaconsInRegion(beaconRegionGeneral)
        setIsRanging(true)
    }


    if(application.respondsToSelector("registerUserNotificationSettings:")) {
        application.registerUserNotificationSettings(
            UIUserNotificationSettings(
                forTypes: UIUserNotificationType.Alert | UIUserNotificationType.Sound,
                categories: nil
            )
        )
    }

    return true
}

func checkBackgroundPermission() {
    sendLocalNotificationWithMessage("checkBackgroundPermission", playSound: false)
    println("checkBackgroundPermission")
}

func locationManager(manager: CLLocationManager!, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
    sendLocalNotificationWithMessage("didChangeAuthorizationStatus", playSound: true)
    println("didChangeAuthorizationStatus")
}

1 个答案:

答案 0 :(得分:1)

您可以使用以下委托方法(来自CLLocationManagerDelegate协议)来获取通知。

 optional func locationManager(_ manager: CLLocationManager!, didChangeAuthorizationStatus status: CLAuthorizationStatus)