我正在尝试获取位置。问题是func locationManager(_ manager:CLLocationManager,didChangeAuthorization status:CLAuthorizationStatus)和locationManager(_ manager:CLLocationManager,didUpdateLocations locations:[CLLocation])从未被调用。
当我第二次调用startLocation时:
DispatchQueue.global(qos: .background).async {
let gpsController = GPSController()
gpsController.startLocation()
sleep(10)
DispatchQueue.main.async {
gpsController.startLocation()
}
}
字符串
我可以看到批准。
import Foundation
import CoreLocation
class GPSController : NSObject, CLLocationManagerDelegate{
let locationManager: CLLocationManager = CLLocationManager()
static var lastLocation : CLLocation? = nil
func startLocation(){
locationManager.delegate = self
// Sprawdź status usług lokalizacyjnych
if CLLocationManager.locationServicesEnabled() {
switch locationManager.authorizationStatus {
case .notDetermined:
print("notDetermined")
locationManager.requestWhenInUseAuthorization()
break
case .restricted, .denied:
print("Denied")
break
case .authorizedWhenInUse, .authorizedAlways:
locationManager.startUpdatingLocation()
print("authorizedWhenInUse")
case .authorized:
print("authorized")
break
@unknown default:
print("@unknown")
break
}
} else {
print("turn off")
}
}
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
print("didChangeAuthorization")
if manager.authorizationStatus == .authorizedWhenInUse {
locationManager.startUpdatingLocation()
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
print("didChangeAuthorization")
for currentLocation in locations{
Loge("Location : \(currentLocation)")
GPSController.lastLocation = currentLocation
}
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print("error")
}
型
}
1条答案
按热度按时间balp4ylt1#
你把
GPSController
放在一个全局队列中,这样控制器的作用域就不会从队列中逃逸出来。队列执行后,控制器就会被移除。它不再监听那个delegate
。你可以通过deinit
检查它,它会在sleep(10)
之后打印出来。字符串
解决方法:将
GPSController
放在一个类/控制器中,以保持引用。型
顺便说一句,委托应该被分配一次,所以我更愿意把它放在
init
中。型