为什么'CLLocationManager.locationServicesEnabled()'默认为true?

时间:2016-01-24 03:29:14

标签: ios swift core-location cllocationmanager

我在Xcode中注意到以下一个简单的全新项目。

如果在ViewController.swift文件中导入CoreLocation,然后在viewDidLoad方法中添加...

打印(CLLocationManager.locationServicesEnabled())

...,当应用程序在模拟器中运行时Xcode打印出true。我原以为默认情况下会禁用位置服务,但正如您自己可以看到的那样,情况正好相反。如果我想要我可以添加更多代码来收集有关用户的位置信息,所有这些都无需征得许可。

有人可以解释为什么会这样吗?

2 个答案:

答案 0 :(得分:11)

据我所知,CLLocationManager.locationServicesEnabled()将返回是否在设备上启用了位置服务,而不仅仅是针对该应用。因此,即使为该应用程序禁用了位置服务,如果它们已为设备启用,我认为仍然会返回true,如文档所述:https://developer.apple.com/library/ios/documentation/CoreLocation/Reference/CLLocationManager_Class/#//apple_ref/occ/clm/CLLocationManager/locationServicesEnabled

在我的应用中,我将其设置为:

    //check if location services are enabled at all
    if CLLocationManager.locationServicesEnabled() {

        switch(CLLocationManager.authorizationStatus()) {
        //check if services disallowed for this app particularly
        case .Restricted, .Denied:
            print("No access")
            var accessAlert = UIAlertController(title: "Location Services Disabled", message: "You need to enable location services in settings.", preferredStyle: UIAlertControllerStyle.Alert)

            accessAlert.addAction(UIAlertAction(title: "Okay!", style: .Default, handler: { (action: UIAlertAction!) in UIApplication.sharedApplication().openURL(NSURL(string:UIApplicationOpenSettingsURLString)!)
            }))

            presentViewController(accessAlert, animated: true, completion: nil)

        //check if services are allowed for this app
        case .AuthorizedAlways, .AuthorizedWhenInUse:
            print("Access! We're good to go!")
        //check if we need to ask for access
        case .NotDetermined:
            print("asking for access...")
            manager.requestAlwaysAuthorization()
        }
    //location services are disabled on the device entirely!
    } else {
        print("Location services are not enabled")

    }
祝你好运!

答案 1 :(得分:0)

Swift 3.1函数返回状态和错误消息

func isLocationEnabled() -> (status: Bool, message: String) {
    if CLLocationManager.locationServicesEnabled() {
        switch(CLLocationManager.authorizationStatus()) {
        case .notDetermined, .restricted, .denied:
            return (false,"No access")
        case .authorizedAlways, .authorizedWhenInUse:
            return(true,"Access")
        }
    } else {
        return(false,"Turn On Location Services to Allow App to Determine Your Location")
    }
}