在Swift代码中没有调用CLLocationManagerDelegate方法

时间:2014-10-17 22:25:04

标签: ios swift core-location cllocationmanager

我正在尝试创建一个简单的应用程序,找出某个人所在的区域,但是我被卡住了,因为当应用程序运行并找到位置时,没有调用任何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")
  } 
}

我已经放入了断点,所以我知道代码永远不会被调用。我已经进入并在应用程序运行时手动启用了位置服务。

3 个答案:

答案 0 :(得分:2)

尝试致电

func locationManager(manager: CLLocationManager!, didUpdateToLocation newLocation: CLLocation!, fromLocation oldLocation: CLLocation!)

而不是你现在正在制作的委托电话...... 我遇到了问题:

func locationManager(manager: CLLocationManager!, didUpdateLocations locations:  [AnyObject]!)

以及。但是使用上面的委托调用解决了我的问题。

修改(没有正确阅读问题......)

你永远不会要求获得许可,这就是你没有获得弹出窗口的原因。请致电以下人员: locationManager.requestWhenInUseAuthorization()

这是非常重要的一步,如果您没有要求用户授权您的应用,那么您的应用将无法使用

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

截图:

enter image description here

答案 1 :(得分:0)

以下答案问答给了我所需的解决方案。

CLLocationManager authorization issue iOS 8

最终,如果您在iOS上运行,则必须添加密钥

NSLocationAlwaysUsageDescription(请求位置数据始终可用时)

OR

NSLocationWhenInUseUsageDescription(仅在您的应用运行时请求使用位置数据时)

如果您不这样做,默认情况下,您的应用将拒绝位置服务访问,并且不会提示用户允许它。

答案 2 :(得分:0)

private let loctionManager = CLLocationManager() // Here

class YourViewController: ViewController {
    loctionManager.delegate = self
    loctionManager.requestWhenInUseAuthorization()
}

extension YourViewController: CLLocationManagerDelegate {
    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
        if (status == .authorizedWhenInUse) {
            // do something
        }
    }
}

.plist
Property List
Key: Privacy - Location When In Use Usage Description
Type: String
Value: Use to add a location to your rap.
OR
Source code
<key>NSLocationWhenInUseUsageDescription</key>
<string>Use to add a location to your rap.</string>
相关问题