当用户被授予访问用户当前位置的权限时,我试图显示用户当前位置,并将图钉放入用户的当前位置。我正在使用 Xcode 15.3 和 Swift 版本 5.10 。我已将需求添加到 info.plit 中,并使用插座为其定义必要的功能。但问题是我在控制台中收到以下警告..
如果在主线程上调用此方法可能会导致 UI 无响应。相反,请考虑等待
-locationManagerDidChangeAuthorization:
回调并首先检查 authorizationStatus
。
这是控制台中的错误消息,当我运行应用程序时,仅在应用程序中显示英国地图,但我希望通过图钉显示用户当前位置。
错误域=kCLErrorDomain代码=1“(空)”
这是 info.plit 的屏幕截图..这是我运行应用程序时的屏幕截图..
这是代码..
import UIKit
import MapKit
class ViewController: UIViewController, CLLocationManagerDelegate {
@IBOutlet weak var myMap: MKMapView!
let locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
if (CLLocationManager.locationServicesEnabled()) {
locationManager.requestLocation()
locationManager.startUpdatingLocation()
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let userLocation = locations.first {
manager.stopUpdatingLocation()
let coordinate = CLLocationCoordinate2D(latitude: locationManager.location?.coordinate.latitude ?? 0.0, longitude: locationManager.location?.coordinate.longitude ?? 0.0)
let span = MKCoordinateSpan(latitudeDelta: 0.1, longitudeDelta: 0.1)
let region = MKCoordinateRegion(center: coordinate, span: span)
myMap.setRegion(region, animated: true)
let myPin = MKPointAnnotation()
myPin.coordinate = coordinate
myPin.title = "Hey There"
myPin.subtitle = "I am here"
myMap.addAnnotation(myPin)
}
}
func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {
switch manager.authorizationStatus {
case .authorizedAlways:
return
case .authorizedWhenInUse:
return
case .notDetermined:
locationManager.requestWhenInUseAuthorization()
case .restricted:
locationManager.requestWhenInUseAuthorization()
case .denied:
return
@unknown default:
locationManager.requestWhenInUseAuthorization()
}
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: any Error) {
print(error)
}
}
NSLocationAlwaysAndWhenInUseUsageDescription
和
NSLocationWhenInUseUsageDescription
键。在
viewDidLoad
中,您可以通过以下方式获取当前的
authorizationStatus
:
switch locationManager.authorizationStatus {
case .notDetermined:
//Request the first time
locationManager.requestAlwaysAuthorization()
case .denied, .restricted:
//TODO: Handle when user denied location permission
//Force to open location permission in Setting for example
break
default:
break
}
然后 didChangeAuthorization
将触发
startUpdatingLocation
,因为从现在开始,它就可以工作了。
func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {
if manager.authorizationStatus == .authorizedWhenInUse || manager.authorizationStatus == .authorizedAlways {
locationManager.startUpdatingLocation()
}
}
当当前位置聚焦时,您可以根据需要保留stopUpdatingLocation
,或者将其放在
deinit
/
viewDidDisappear
。