【问题标题】:Getting user location in swift快速获取用户位置
【发布时间】:2014-09-29 22:05:38
【问题描述】:

这是我的代码:

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

    }


  }
}

此代码不返回任何内容(它应该打印经度)。这似乎没问题,因为如果我移动

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

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

谢谢!

【问题讨论】:

    标签: ios swift


    【解决方案1】:
    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"
    }
    

    【讨论】:

      【解决方案2】:

      你在 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 函数中。

      然后它应该显示一个警报,要求获得使用位置服务的权限。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-04-30
        • 2017-08-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多