为啥'CLLocationManager.locationServicesEnabled()'默认为真?

Posted

技术标签:

【中文标题】为啥\'CLLocationManager.locationServicesEnabled()\'默认为真?【英文标题】:Why is 'CLLocationManager.locationServicesEnabled()' true by default?为什么'CLLocationManager.locationServicesEnabled()'默认为真? 【发布时间】:2016-01-24 03:29:14 【问题描述】:

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

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

打印(CLLocationManager.locationServicesEnabled())

...,当应用程序在模拟器中运行时,Xcode 打印出 true。我原以为默认情况下会禁用位置服务,但正如您自己所见,事实恰恰相反。如果我愿意,我可以添加更多代码来收集有关用户的位置信息,而这一切都无需请求许可。

谁能解释这是为什么?

【问题讨论】:

【参考方案1】:

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

    

祝你好运!

【讨论】:

完美。正是我需要的知识。 太棒了!如果我有帮助,您可以将其标记为答案 :)【参考方案2】:

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")
    

【讨论】:

以上是关于为啥'CLLocationManager.locationServicesEnabled()'默认为真?的主要内容,如果未能解决你的问题,请参考以下文章

为啥 DataGridView 上的 DoubleBuffered 属性默认为 false,为啥它受到保护?

为啥需要softmax函数?为啥不简单归一化?

为啥 g++ 需要 libstdc++.a?为啥不是默认值?

为啥或为啥不在 C++ 中使用 memset? [关闭]

为啥临时变量需要更改数组元素以及为啥需要在最后取消设置?

为啥 CAP 定理中的 RDBMS 分区不能容忍,为啥它可用?