[英]Failing to display user location SwiftUI
在我發布我的代碼之前,我應該告訴你我的代碼在一個項目上運行,而在第二個項目上沒有運行!
我得到的錯誤是:
[MKCoreLocationProvider] CLLocationManager(<CLLocationManager: 0x280cfc050>) for <MKCoreLocationProvider: 0x283cd0870> did fail with error: Error Domain=kCLErrorDomain Code=1 "(null)"
這就是為什么我的代碼在一個項目上運行而我現在正在處理的項目卻沒有的原因。 我使用的是相同版本的 ios 14。
import Foundation
import UIKit
import SwiftUI
import MapKit
struct MapView: UIViewRepresentable {
typealias UIViewType = UIView
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
func makeUIView(context: Context) -> UIView {
let map = MKMapView()
map.delegate = context.coordinator
map.showsUserLocation = true
return map
}
func updateUIView(_ uiView: UIView, context: Context) {
}
}
import Foundation
import MapKit
class Coordinator: NSObject, MKMapViewDelegate {
var control: MapView
init(_ control: MapView) {
self.control = control
}
}
class GetUserLocation: NSObject, ObservableObject, CLLocationManagerDelegate {
let locationManager = CLLocationManager()
@Published var location: CLLocation? = nil
override init() {
super.init()
self.locationManager.delegate = self
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
self.locationManager.distanceFilter = kCLDistanceFilterNone
self.locationManager.requestWhenInUseAuthorization()
self.locationManager.startUpdatingLocation()
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let location = locations.last else {
return
}
self.location = location
}
}
在有了一些 rest 之后,我開始調試問題,我發現init()
function 沒有在文件3. Location manager
中被調用。
我試圖從其他文件初始化 object 並猜測它的工作沒有任何問題,這里是另一個有線的東西!
所以init()
function 被其他文件調用,但是在4. UserLocationMapView
它沒有被調用,我不明白為什么!
喝了一杯咖啡后,我發現在SceneDelegate
中我調用了錯誤的視圖文件,我的UserLocationMapView
顯示了 map,但是我在SceneDelegate
中調用了3. MapView
。
這是一個愚蠢的錯誤,當您在SceneDelegate
中調用這兩個文件時,它們會毫無問題地顯示 map。 因此,當您看到 map 顯示在模擬器中時,您會認為它正在工作,但是其中一個調用init()
function 而其中一個沒有它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.