【问题标题】:CoreLocation requestWhenInUseAuthorization() not working in SwiftCoreLocation requestWhenInUseAuthorization() 在 Swift 中不起作用
【发布时间】:2015-07-27 22:32:54
【问题描述】:

我希望我的应用显示用户的位置,但它不要求 WhenInUseAuthorization。我在 Info.plist 中添加了 NSLocationWhenInUseUsageDescription 键。我在 iOS 模拟器中尝试了模拟位置和实际设备。

import UIKit
import MapKit
import CoreLocation

class ViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {

    @IBOutlet weak var mapView: MKMapView!

    var locationManager = CLLocationManager()

    override func viewDidLoad() {
        super.viewDidLoad()
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest

        if CLLocationManager.authorizationStatus() == .NotDetermined {
            self.locationManager.requestWhenInUseAuthorization()
        }
    }

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

        if CLLocationManager.authorizationStatus() == .AuthorizedWhenInUse {
            locationManager.startUpdatingLocation()
            mapView.showsUserLocation = true

            let userLocation = CLLocationCoordinate2DMake(locationManager.location.coordinate.latitude, locationManager.location.coordinate.longitude)
            mapView.region = MKCoordinateRegionMakeWithDistance(userLocation, 100, 100)

        } else {

            let defaultLocation = CLLocationCoordinate2DMake(45.5017, -73.5673)
            mapView.region = MKCoordinateRegionMakeWithDistance(defaultLocation, 100, 100)
        }
    }
}

【问题讨论】:

    标签: ios swift cocoa-touch core-location


    【解决方案1】:

    这是我的错误,我在测试文件夹的 Info.plist 而不是主项目的 plist 中添加了 NSLocationWhenInUseUsageDescription 键。

    【讨论】:

      【解决方案2】:

      您是否更改了模拟器上的用户位置?不改的话,是拿不到“用户位置”的。

      【讨论】:

      • 我确实改变了它,但它没有用。我还在我的 iphone 6 上试过,但它没有获取我的用户位置。
      • startUpdatingLocation() 被调用了吗?
      • 我不这么认为,我在 startUpdatingLocation() 之后添加了一条打印语句,并且没有控制台输出。另外我刚刚意识到,当我单击构建按钮时,xCode 中的模拟位置和 iOS 模拟器中的自定义位置会自行关闭。
      • 在委托函数处添加控制台调试:func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!)。它至少需要调用一次。
      • 它以 status = (CLAuthorizationStatus) NotDetermined 调用。
      【解决方案3】:

      也许你调用 requestWhenInUseAuthorization 太早了。尝试致电didChangeAuthorizationStatus委托。

      func locationManager(manager: CLLocationManager!, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
          if status == CLAuthorizationStatus.NotDetermined {
              locationManager.requestWhenInUseAuthorization()
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2016-08-26
        • 1970-01-01
        • 2012-09-25
        • 1970-01-01
        • 1970-01-01
        • 2021-06-25
        • 1970-01-01
        • 1970-01-01
        • 2014-08-05
        相关资源
        最近更新 更多