CoreLocation的问题

时间:2016-02-19 10:00:17

标签: swift core-location

出于某种原因,我似乎无法获得用户位置。我买了iOS 9 CookBook并准确地处理了他们的代码

这是ViewController:

import UIKit
import CoreLocation

class ViewController: UIViewController, CLLocationManagerDelegate {

lazy var locationManager: CLLocationManager = {
  let m = CLLocationManager()
  m.delegate = self
  m.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
  return m
}()

func locationManager(manager: CLLocationManager,
  didUpdateLocations locations: [CLLocation]) {
    //TODO: now you have access to the location. do your work
}

func locationManager(manager: CLLocationManager,
  didFailWithError error: NSError) {
  //TODO: handle the error
}

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

  if case .AuthorizedWhenInUse = status{
    manager.requestLocation()
  } else {
    //TODO: we didn't get access, handle this
    print("No Access Granted")
  }

}

@IBAction func requestLocation() {

  locationManager.requestWhenInUseAuthorization()

}

}

控制台中的输出是:

  

无法访问权限

任何想法是怎么回事?我已经在模拟器和设备上测试了这个

编辑:我在故事板上添加了一个按钮,并相应地将其舔到了IBAction。

1 个答案:

答案 0 :(得分:1)

您是否已将NSLocationWhenInUseUsageDescription键添加到plist中? - 该值应该是一个字符串,描述您要使用用户位置的原因。

<key>NSLocationWhenInUseUsageDescription</key>
<string>Required to provide information about your location.</string>

如果一切正常,didUpdateLocations委托方法应该返回一个位置数组,你可以像这样打印出来......

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    for loc in locations {
        print(loc)
    }
}

如果您想持续监控位置,可以拨打manager.startUpdatingLocation()而不是manager.requestLocation()