我正在尝试在WatchKitExtension ExtensionDelegate中读取当前位置坐标。这虽然没有返回任何值。
WatchKitExtension InterfaceController中使用的代码确实返回了该位置。 (由于我在代码中找不到错误,因此绝望地尝试了这一点)
我需要在ExtensionDelegate中执行此代码,因为我希望将检索到的位置传递给ClockKit Complication。
这里是ExtensionDelegate中的代码:(在self.locationManager.requestLocation()之后,委托函数didUpdateLocation / didFailWithError不会被调用)
import WatchKit
import CoreLocation
class ExtensionDelegate: NSObject, WKExtensionDelegate, CLLocationManagerDelegate {
private let locationManager = CLLocationManager()
override init() {
print("ExtensionDelegate: \(NSDate()) - init")
super.init()
self.getLocation()
}
func getLocation(){
print("ExtensionDelegate: \(NSDate()) - getLocation")
locationManager.delegate = self
locationManager.requestAlwaysAuthorization()
locationManager.requestWhenInUseAuthorization()
locationManager.requestLocation()
}
...
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
print("ExtensionDelegate: \(NSDate()) - locationManager didUpdateLocations")
guard let mostRecentLocation = locations.last else { return }
let place = mostRecentLocation.coordinate
print("\(place)")
manager.stopUpdatingLocation()
}
func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
print("ExtensionDelegate: \(NSDate()) - locationManager didFailWithError")
print("CL failed: \(error)")
}
}
这里是InterfaceController中的相同代码,它完美地工作(didUpdateLocation确实被调用):
import WatchKit
import Foundation
import CoreLocation
class InterfaceController: WKInterfaceController, CLLocationManagerDelegate {
private let locationManager = CLLocationManager()
override func awakeWithContext(context: AnyObject?) {
print("InterfaceController: \(NSDate()) - awakeWithContext")
super.awakeWithContext(context)
self.getLocation()
}
func getLocation(){
print("InterfaceController: \(NSDate()) - getLocation")
locationManager.delegate = self
locationManager.requestAlwaysAuthorization()
locationManager.requestWhenInUseAuthorization()
locationManager.requestLocation()
}
...
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
print("InterfaceController: \(NSDate()) - locationManager didUpdateLocations")
guard let mostRecentLocation = locations.last else { return }
let place = mostRecentLocation.coordinate
print("\(place)")
manager.stopUpdatingLocation()
}
func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
print("InterfaceController: \(NSDate()) - locationManager didFailWithError")
print("CL failed: \(error)")
}
}