我想要使用CoreLocation(一旦授予權限)來獲取用戶的CLLocationCoordinate2D,以便我可以將該信息傳遞給優步深度鏈接(在我的TableView內的UIButton被按下後)。位置管理器CLLocationCoordinates didUpdateLocations
我已經想出瞭如何獲取座標作爲CLLocations,並將它們轉換爲didUpdateLocations方法中的CLLocationCoordinates2D,但似乎無法將它們轉移到我的buttonPressed函數中。
任何人都可以解釋我可以如何正確地將座標信息轉移到uberButtonPressed方法?我也對如何讓locationManager在確定合適的位置後停止更新位置感到困惑。任何幫助深表感謝。順便說一句,我用這個實例尤伯杯:https://github.com/kirby/uber
import UIKit
import CoreLocation
import MapKit
class ATableViewController: UITableViewController, CLLocationManagerDelegate {
let locationManager = CLLocationManager()
var location: CLLocation?
var coordinate: CLLocationCoordinate2D?
// Implemented tableView methods etc here...
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
let newLocation = locations.last as! CLLocation
println("DID UPDATE LOCATIONS \(newLocation)")
location = newLocation
coordinate = location!.coordinate
println("WE HAVE THE COORDINATES \(coordinate!.latitude) and \(coordinate!.longitude)") // this prints along with DID UPDATE LOCATIONS
}
func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) {
println("error:" + error.localizedDescription)
}
func uberButtonPressed(sender: UIButton!) {
let senderButton = sender
println(senderButton.tag)
let authStatus: CLAuthorizationStatus = CLLocationManager.authorizationStatus()
if authStatus == .NotDetermined {
locationManager.requestWhenInUseAuthorization()
return
}
if CLLocationManager.locationServicesEnabled() {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.startUpdatingLocation()
}
var pickupLocation = coordinate! // fatal error: unexpectedly found nil while unwrapping an Optional value
println(pickupLocation)
// // Create an Uber instance
// var uber = Uber(pickupLocation: pickupLocation)
//
// Set a few optional properties
// uber.pickupNickname = "OK"
//
// uber.dropoffLocation = CLLocationCoordinate2D(latitude: 47.591351, longitude: -122.332271)
// uber.dropoffNickname = "whatever"
//
// // Let's do it!
// uber.deepLink()
//
}
嗨THX輸入...我嘗試移動pickupLocation到didUpdateLocations和這個工作,我得到座標並正確執行stopUpdatingLocation()。我有點困惑,你的意思是通過調用一個NEW函數來運行func中的其餘代碼uberButtonPressed ...你的意思是我應該取出代碼(來自uberButtonPressed) - 從var uber = Uber(pickup位置:pickup位置!),創建一個單獨的函數,然後從didUpdateLocations調用它?我試過這個,並且pickup位置仍然是零...問題可能是uberButtonPressed運行1st? – SamYoungNY
是的,這是正確的,您應該在停止位置更新後調用新功能。新功能將包括從'var uber = Uber(pickup位置:pickup位置!)開始的代碼'您可以將'pickup位置'傳遞給新函數或使'pickup位置'屬於您的類的屬性,以便您可以從您的新函數被賦值後,在'didUpdateLocation' – rmp
這個工作...你是男人,謝謝你! – SamYoungNY