我正在学习Swift和IOS编程。在升级到Xcode 9和IOS 11模拟器之前,我有这个骨架代码工作正常,但现在它根本不工作,我不知所措。我已经搜索了可能已经改变但没有想出任何东西的东西。我知道这很简单。
在应用程序的plist文件中,我设置了NSLocationWhenInUseUsageDescription键,因此它不会抱怨要求用户许可。该应用程序构建良好,并在模拟器上运行,但它永远不会打印任何位置信息,也不会给出任何错误。在模拟器中,我进入了Debug-> Location并设置了lat / long。
import WatchKit
import Foundation
import CoreLocation
var yourLongitude: Double = 0.0
class InterfaceController: WKInterfaceController, CLLocationManagerDelegate {
var manager: CLLocationManager!
var location: CLLocation!
override func awake(withContext context: Any?) {
super.awake(withContext: context)
// Configure interface objects here.
self.manager = CLLocationManager()
self.manager.delegate = self;
self.manager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
self.manager.requestWhenInUseAuthorization()
self.manager.startUpdatingLocation()
//NSLog("Here")
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let locValue:CLLocationCoordinate2D = manager.location!.coordinate
NSLog("locations = \(locValue.latitude) \(locValue.longitude)")
yourLongitude = locValue.longitude
printLongitude(yourLongitude)
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
NSLog("Error with geolocation " + error.localizedDescription)
}
func printLongitude(_ longitude: Double) {
var longitudeForLabel: String?
if (longitude < 0) {
longitudeForLabel = String(format: "%.03f", abs(longitude)) + "°W"
} else {
longitudeForLabel = String(format: "%.03f", longitude) + "°E"
}
LongitudeLabel.setText(longitudeForLabel!)
manager.stopUpdatingLocation()
//NSLog("Here")
}
override func willActivate() {
// This method is called when watch view controller is about to be visible to user
super.willActivate()
manager.startUpdatingLocation()
NSLog("app in foreground")
}
override func didDeactivate() {
// This method is called when watch view controller is no longer visible
super.didDeactivate()
}
}