我正在尝试使用CoreLocation(一旦获得权限)来获取用户的CLLocationCoordinate2D,以便我可以将该信息传递给Uber深层链接(在我的TableView中按下UIButton之后)。
我已经想出如何将坐标作为CLLocations,并将它们转换为didUpdateLocations方法中的CLLocationCoordinates2D,但似乎无法将它们转移到我的buttonPressed函数。
任何人都可以解释我如何正确地将坐标信息传递给uberButtonPressed方法?我也很困惑如何在确定合适的位置后让locationManager停止更新位置。任何帮助深表感谢。顺便说一句,我使用它来实例化Uber: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()
//
}
答案 0 :(得分:1)
您应该将var pickupLocation = coordinate!
移到didUpdateLocations
。分配完成后,您也可以从locationManager.stopUpdatingLocation()
内部调用'didUpdateLocation
或调整您的值,以便不断更新。停止locationManager后,调用一个NEW函数来运行当前func uberButtonPressed
答案 1 :(得分:1)
我遇到了同样的问题。
而不是像这样调用委托方法:
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
debugPrint("NOT CALLED-- didUpdateLocations AnyObject")
}
我换成了:
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
debugPrint("CALLED-- didUpdateLocations CLLocation")
}