由于某些奇怪的原因,它会在我第一次尝试运行该程序时崩溃,但是如果我在模拟器仍在运行时再次运行它,它将运行正常。这是导致问题的代码片段。
class CityList : NSObject, CLLocationManagerDelegate {
// stored properties
var cities: [City]
var currentLocation: CLLocation? = nil
static let sharedInstance = CityList()
static let firstNotif = Notification.Name(rawValue: "test")
static let secondNotif = Notification.Name(rawValue: "test2")
let locationManager = CLLocationManager()
// initializers
override init () {
cities = [
City(name: "Medford", state: "Oregon", latitude: 42.3266667, longitude: -122.8744444),
City(name: "Seattle", state: "Washington", latitude: 47.6063889, longitude: -122.3308333),
City(name: "Grants, Pass", state: "Oregon", latitude: 42.4391667, longitude: -123.3272222),
City(name: "Applegate", state: "Oregon", latitude: 42.2570662, longitude: -123.1683833),
City(name: "San Francisco", state: "California", latitude: 37.775, longitude: -122.4183333)
]
super.init()
locationManager.delegate = self
locationManager.requestWhenInUseAuthorization()// request user authorization
locationManager.requestAlwaysAuthorization()
locationManager.startUpdatingLocation()
currentLocation = locationManager.location
cities.append(City(name: "test", state: "test", location: currentLocation!))
}
答案 0 :(得分:0)
您必须实现locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
,CLLocationManagerDelegate
才能正常工作
import CoreLocation
public class Location: NSObject, CLLocationManagerDelegate {
private let manager = CLLocationManager()
override convenience public init() {
self.init()
manager.desiredAccuracy = kCLLocationAccuracyThreeKilometers
manager.delegate = self
manager.requestWhenInUseAuthorization()
manager.requestAlwaysAuthorization()
manager.startUpdatingLocation()
}
public func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print("Error", error)
}
public func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let location = locations.first else {
return
}
print(location.coordinate.longitude)
print(location.coordinate.latitude)
}
}