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

6
我注意到在Xcode中的一个全新项目中存在以下情况。
如果在ViewController.swift文件中导入CoreLocation,然后在viewDidLoad方法中添加... print(CLLocationManager.locationServicesEnabled())
...当应用程序在模拟器中运行时,Xcode会打印出true。我本以为默认情况下位置服务会被禁用,但事实是相反的。如果我想,我可以添加更多代码来收集用户的位置信息,所有这些都不需要请求权限。
有人能解释一下这是为什么吗?
2个回答

15
据我所知,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")

    }

祝你好运!


太好了。正是我所需要的知识。 - user3915477
太棒了!如果我有帮助的话,您可以将其标记为答案 :) - Brendan Chang

1

返回状态和错误信息的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")
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接