快速获取用户位置

时间:2014-09-29 22:05:38

标签: ios swift

这是我的代码:

import Foundation
import CoreLocation

class ViewController: UIViewController, CLLocationManagerDelegate {

let locationManager = CLLocationManager()

@IBOutlet weak var locationLabel: UILabel!

var coord: CLLocationCoordinate2D?

override func viewDidLoad() {
    super.viewDidLoad()
    locationManager.delegate = self
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.requestWhenInUseAuthorization()
    if CLLocationManager.authorizationStatus() == CLAuthorizationStatus.Authorized {
        locationManager.startUpdatingLocation()
        println(coord!.longitude)
        locationLabel.text = "location found"
    }

    func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
        var locationArray = locations as NSArray
        var locationObj = locationArray.lastObject as CLLocation
        coord = locationObj.coordinate

    }


  }
}

此代码不返回任何内容(它应打印经度)。这似乎是O.K,因为如果我搬家

            locationManager.startUpdatingLocation()
        println(coord!.longitude)

在if语句之外,Xcode抛出一个运行时错误,并在解开Optional值时意外地发现nil。我不明白为什么呢?系统要求我允许使用我的位置。

谢谢!

2 个答案:

答案 0 :(得分:3)

override func viewDidLoad() {
  super.viewDidLoad()
  // Do any additional setup after loading the view, typically from a nib.
  locationManager = CLLocationManager()
  locationManager.delegate = self
  locationManager.desiredAccuracy = kCLLocationAccuracyBest
  locationManager.requestAlwaysAuthorization()
  locationManager.startUpdatingLocation()
}

func locationManager(manager:CLLocationManager, didUpdateLocations locations:AnyObject[] {
  println("locations = \(locations)")
  gpsResult.text = "success"
}

答案 1 :(得分:0)

你在iOS8上运行吗?假设:

1.您需要初始化 self.locationManager = CLLocationManager()

2.在之后,请致电self.locationManager.requestAlwaysAuthorization();self.locationManager.delegate = self之前)

3.使用外部文本编辑器(相应地更改文本)将这些键添加到Info.plist中

<key>NSLocationWhenInUseUsageDescription</key>
<string>This is needed for iOS8 and up (when in use)</string>

<key>NSLocationAlwaysUsageDescription</key>
<string>This is needed for iOS8 and up (always)</string>

4.您致电println(coord!.longitude)的地方可能为时过早。将其移至locationManager函数。

然后它应该显示一个警告,要求获得使用位置服务的许可。