在Swift代码中未调用CLLocationManagerDelegate方法

Mar*_*eid 5 core-location cllocationmanager ios swift

我正在尝试创建一个简单的应用程序,以找出某人所在的区域,但是由于应用程序运行并找到位置时,不会调用任何CLLocationManagerDelegate方法,所以我陷入了困境。

如果相关,我也不会看到对话框,询问我是否允许该应用使用位置信息。

这是我到目前为止的内容-

import UIKit
import CoreLocation

class ViewController: UIViewController, CLLocationManagerDelegate {

@IBOutlet weak var locationLabel : UILabel!

var locationManager = CLLocationManager()
let geocoder = CLGeocoder ()

override func viewDidLoad() {
  super.viewDidLoad()
  // Do any additional setup after loading the view, typically from a nib.

  locationManager.delegate = self
  locationManager.desiredAccuracy = kCLLocationAccuracyBest
  locationManager.startUpdatingLocation()
}

override func viewDidDisappear(animated: Bool) {
  locationManager.stopUpdatingLocation()
}

override func didReceiveMemoryWarning() {
  super.didReceiveMemoryWarning()
  // Dispose of any resources that can be recreated.
}

func locationManager(manager: CLLocationManager!, didUpdateLocations locations:  [AnyObject]!) {
  geocoder.reverseGeocodeLocation(locations.last as CLLocation, completionHandler: {(placemark, error) in
    if (error != nil) {
      println("Error")
    } else {
      let pm = placemark.first as CLPlacemark

      println(pm)
    }
  })
}

func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) {
    println("Epic Fail")
  } 
}
Run Code Online (Sandbox Code Playgroud)

我已经设置了断点,所以我知道代码永远不会被调用。我也进去了,并且还在运行该应用程序时手动为其打开了位置服务。

Chr*_*ris 3

尝试打电话

func locationManager(manager: CLLocationManager!, didUpdateToLocation newLocation: CLLocation!, fromLocation oldLocation: CLLocation!)
Run Code Online (Sandbox Code Playgroud)

而不是您现在拨打的代表电话...我遇到了问题:

func locationManager(manager: CLLocationManager!, didUpdateLocations locations:  [AnyObject]!)
Run Code Online (Sandbox Code Playgroud)

还有。但使用上面的委托调用解决了我的问题。

编辑(没有正确阅读问题......)

您从不请求许可,这就是为什么您没有收到弹出窗口的原因。请拨打以下电话: locationManager.requestWhenInUseAuthorization()

这是非常重要的一步,如果您没有请求用户对您的应用程序进行授权,您的应用程序将无法运行

如果运行 iOS8,添加NSLocationWhenInUseUsageDescription到 .plist 文件也很重要。

截屏:

在此输入图像描述

  • 好的@Mark Reid,您运行的是哪个 iOS 版本?请记住,您必须将以下键/值添加到 .plist 文件中:`NSLocationWhenInUseUsageDescription`:“我需要使用您的位置来实现这个和另一个” (2认同)