2015-12-14 18 views
0

我試圖做一個應用程序,顯示項目取決於他們的位置。不幸的是,我的代碼仍然運行,不會等到找到用戶位置。它返回一個零值。我怎樣才能避免這種情況?這是可能的,我怎麼能實現它。我的代碼如下我需要我的功能的用戶位置,但它返回無

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功能要求的位置運行

+0

選項卡上單擊符號'startUpdatingLocation()'並閱讀'Discussion' – vadian

回答

1

在你的代碼you're錯過了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. 當你不拋出一個錯誤'T有一個位置

如果你想獲得lat和長時間只使用下面的代碼片段中locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation])

let location:CLLocationCoordinate2D = manager.location!.coordinate 
lat = String(location.latitude) 
long = String(location.longitude) 
+0

所以我試過這個。但是當我打電話給'didupdatelocations'時,我放了一些打印語句來檢查它是否在那裏。在我的調試控制檯中,他們不顯示,所以我假設它進入內部。有什麼我失蹤? –

+0

您是否將didFailWithError添加到了?這可能是您無法加載位置。 @IkeTrout –

相關問題