【问题标题】:Location is returning nil位置返回零
【发布时间】:2017-09-07 18:53:29
【问题描述】:

我整天都被这个问题困扰。在用户选择“使用时允许位置”后,我的应用程序没有更新位置,导致到处都出现 nil

最初我使用 mapView.userLocation 作为查找用户位置的一种方式,但是当我开始使用 CLLocationManager 时它停止工作。

我从顶部导入 CoreLocation 并在我的类中添加 CLLocationManagerDelegate。

在 viewDidLoad() 上面我有 让 locationManager = CLLocationManager() 在 viewDidLoad 我有 locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyBest

现在我要检查用户是否给予批准或者他们是否只是拒绝它的方式是通过这种方法

 switch CLLocationManager.authorizationStatus(){
case.authorizedWhenInUse:
        print(mapView.userLocation?.coordinate)
        mapView.setCenter((mapView.userLocation?.coordinate)!, zoomLevel: 12, animated: true)
        break
    case.notDetermined:
        locationManager.requestWhenInUseAuthorization()
        break
    case .restricted, .denied:
        let alertController = UIAlertController(
            title: "Background Location Access Disabled",
            message: "In order to access this feature you need to allow  to access your location while in use", preferredStyle: .alert)
        let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
        alertController.addAction(cancelAction)

        let openAction = UIAlertAction(title: "Open Settings", style: .default, handler: {(action) in
            if let url = NSURL(string:UIApplicationOpenSettingsURLString) {
                UIApplication.shared.openURL(url as URL)
            }
        })
        alertController.addAction(openAction)
        self.present(alertController, animated: true, completion: nil)
        break
    default: locationManager.requestWhenInUseAuthorization()
    }

我将它分为三个部分,一个是用户按下一个按钮以放大他们当前的位置,一个是在用户周围搜索,最后一个是在 viewDidLoad 中。如果用户从将他们发送到他们的设置的提示中选择了选项,并且他们更改了他们的位置设置,那么当他们被重定向回我的应用程序时,什么也不会发生,如果我做任何涉及用户位置的事情,它就会崩溃。

我尝试过使用 startUpdatingLocation 但这根本没有做任何事情,当我尝试从 mapView.userLocation 捕获用户位置时,它只是显示为 nil。

我整天都在为此苦恼,所以任何形式的帮助都将不胜感激

【问题讨论】:

  • 你在 plist 中添加了 NSLocationWhenInUseUsageDescription 和 NSLocationAlwaysUsageDescription 吗?
  • 你在哪里写mapView.userLocation?
  • 您在哪里签入设备?还是在模拟器中?
  • @SivajeeBattina 在 case.authorizedWhenInUser 我使用 mapView.setCenter((mapView.userLocation?.coordinate)! 但它返回 nil,我正在模拟器中检查它
  • 您在哪里签入设备?还是在模拟器中?

标签: ios swift google-maps location cllocationmanager


【解决方案1】:

试试这个:在模拟器中选择 Debug -> Location -> Some Location。并重启你的应用

【讨论】:

    【解决方案2】:

    我也得到了同样的结果,尝试使用返回 0.0000、0.00000 的 CLlocation 管理器的 loaction 属性。最后使用了didUpdateloaction

    【讨论】:

      猜你喜欢
      • 2015-08-11
      • 1970-01-01
      • 1970-01-01
      • 2017-03-20
      • 1970-01-01
      • 1970-01-01
      • 2017-06-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多