[英]SwiftUI: How to get the current location of user?
I'm trying to get the current location of the user and then display it on a map.我正在尝试获取用户的当前位置,然后将其显示在地图上。 So far I have the following code.到目前为止,我有以下代码。 The problem is that I keep getting this error Static member 'authorizationStatus' cannot be used on instance of type 'CLLocationManager'
And when I change line 46 to问题是我不断收到此错误Static member 'authorizationStatus' cannot be used on instance of type 'CLLocationManager'
并且当我将第 46 行更改为
if CLLocationManager.authorizationStatus() == .authorizedWhenInUse{如果 CLLocationManager.authorizationStatus() == .authorizedWhenInUse{
I get this warning我收到这个警告
'authorizationStatus()' was deprecated in iOS 14.0 'authorizationStatus()' 在 iOS 14.0 中被弃用
I tried looking at other stackoverflow posts but I don't really get it.我尝试查看其他 stackoverflow 帖子,但我真的不明白。 Can someone please help me out.有人可以帮我吗。 Btw I'm not that advanced so would appreciate it if you had some patience.顺便说一句,我不是那么先进,所以如果您有耐心,我将不胜感激。 I got the code from a tutorial I'm following, so I don't fully understand all of it to perfection我从我正在关注的教程中获得了代码,所以我并没有完全理解它的全部内容
import SwiftUI
import MapKit
struct ContentView: View {
var body: some View {
Home()
}
}
struct Home: View{
@State var region = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: 13.086, longitude: 80.2769), latitudinalMeters: 1000, longitudinalMeters: 1000)
@State var tracking : MapUserTrackingMode = .follow
@State var manager = CLLocationManager()
@StateObject var managerDelegate = locationDelegate()
var body: some View {
VStack{
Map(coordinateRegion: $region, interactionModes: .all, showsUserLocation: true, userTrackingMode: $tracking)
}.onAppear{
manager.delegate = managerDelegate
}
}
}
class locationDelegate: NSObject,ObservableObject,CLLocationManagerDelegate{
// Checking authorization status...
func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {
**// THIS IS LINE 46**
if manager.authorizationStatus() == .authorizedWhenInUse{
print("Authorized")
manager.startUpdatingLocation()
} else {
print("not authorized")
manager.requestWhenInUseAuthorization()
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
print("lew location")
}
}
是的,它已被弃用,赞成使用同名属性而不是函数,请尝试不带括号...
if manager.authorizationStatus == .authorizedWhenInUse {
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.