获取错误消息“委托必须回复位置管理器:didfailwitherror:''尝试使用Swift在iOS上获得GPS坐标时
在尝试使用(Swift,SwiftUi)在以下教程上获得iOS上的GPS坐标时,我会收到以下错误消息:
错误消息
Thread 1: "Delegate must respond to locationManager:didFailWithError:"
教程的URL
https://www.hackingwithswift.com/quick-start/swiftui/how-to-read-the-users-location-using-locationbutton
我的问题是:
- 教程不完整吗?
- 我是否必须添加一些其他代码才能尝试此应用?
- 错误消息是什么意思?
代码
(取自教程)是:
import SwiftUI
import CoreLocation
import CoreLocationUI
class LocationManager: NSObject, ObservableObject, CLLocationManagerDelegate {
let manager = CLLocationManager()
@Published var location: CLLocationCoordinate2D?
override init() {
super.init()
manager.delegate = self
}
func requestLocation() {
manager.requestLocation()
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
location = locations.first?.coordinate
}
}
struct ContentView: View {
@StateObject var locationManager = LocationManager()
var body: some View {
VStack {
if let location = locationManager.location {
Text("Your location: \(location.latitude), \(location.longitude)")
}
LocationButton {
locationManager.requestLocation()
}
.frame(height: 44)
.padding()
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
I'm getting the following error message when trying to get GPS coordinates on iOS using (Swift, SwiftUI), based on the following tutorial:
The error message
Thread 1: "Delegate must respond to locationManager:didFailWithError:"
The URL of the tutorial
https://www.hackingwithswift.com/quick-start/swiftui/how-to-read-the-users-location-using-locationbutton
My question is:
- Is the tutorial incomplete?
- Do I have to add some additional code to try out this app?
- What does the error message mean?
The code
(taken from the tutorial) is:
import SwiftUI
import CoreLocation
import CoreLocationUI
class LocationManager: NSObject, ObservableObject, CLLocationManagerDelegate {
let manager = CLLocationManager()
@Published var location: CLLocationCoordinate2D?
override init() {
super.init()
manager.delegate = self
}
func requestLocation() {
manager.requestLocation()
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
location = locations.first?.coordinate
}
}
struct ContentView: View {
@StateObject var locationManager = LocationManager()
var body: some View {
VStack {
if let location = locationManager.location {
Text("Your location: \(location.latitude), \(location.longitude)")
}
LocationButton {
locationManager.requestLocation()
}
.frame(height: 44)
.padding()
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
正如Kishan Bhatiya评论中建议的那样,代码的以下添加(通过提供错误处理):
As suggested in the comments by Kishan Bhatiya, the following addition to the code fixes it (by providing error handling):