我要求用户定位我的功能,但它返回nil

时间:2015-12-14 22:11:39

标签: ios swift cllocation

我正在尝试创建一个根据位置显示项目的应用。不幸的是我的代码仍在运行,并且不会等到我找到用户位置。它返回一个nil值。我怎么能避免这个?这是可能的,我怎样才能实现它。我的代码在

之下
 override func viewDidLoad() {
    super.viewDidLoad()
    // check if locations eabled
     print("I got here 1")
    if CLLocationManager.locationServicesEnabled() {
        self.locManager.delegate = self
        self.locManager.desiredAccuracy = kCLLocationAccuracyBest
        self.locManager.requestWhenInUseAuthorization()
        self.locManager.startUpdatingLocation()
        print("I got here 2")
    }
    else {
        print ("Locations not enabled")
    }

    refresher = UIRefreshControl()
    refresher.attributedTitle = NSAttributedString(string: "Pull to Refresh")
    refresher.addTarget(self, action: "LoadItems", forControlEvents: UIControlEvents.ValueChanged)

    self.tableView.addSubview(refresher)

   LoadItems()

}

我的LoadItems函数需要运行位置

1 个答案:

答案 0 :(得分:1)

在您的代码中,您错过了locationManager.startUpdatingLocation()。将其添加到CLLocationManager.locationServicesEnabled() if-statement中,然后添加这两个功能

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
   // Here you can call a function when you have a location

   // And stop updating the location if you don´t need it anymore
   locationManager.stopUpdatingLocation()
}

func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
    print("Failed to find user´s location: \(error.localizedDescription)")
}

这样你就可以确保

  1. 在致电您的方法时有一个位置
  2. 当您没有位置时发生错误
  3. 如果您想获得lat和long,请使用locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation])

    中的下方代码段
    let location:CLLocationCoordinate2D = manager.location!.coordinate
    lat = String(location.latitude)
    long = String(location.longitude)