【问题标题】:SwiftUI: How to get the current location of user?SwiftUI:如何获取用户的当前位置?
【发布时间】:2021-07-22 20:31:36
【问题描述】:

我正在尝试获取用户的当前位置,然后将其显示在地图上。到目前为止,我有以下代码。问题是我不断收到此错误Static member 'authorizationStatus' cannot be used on instance of type 'CLLocationManager' 当我将第 46 行更改为

如果 CLLocationManager.authorizationStatus() == .authorizedWhenInUse{

我收到此警告

'authorizationStatus()' 在 iOS 14.0 中已弃用

我尝试查看其他 stackoverflow 帖子,但我真的不明白。有人可以帮帮我吗。 顺便说一句,我不是那么先进,所以如果你有耐心的话,我会很感激的。我从我正在关注的教程中获得了代码,所以我并没有完全理解它的全部内容

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")
    }
}

【问题讨论】:

  • 这是一个工作示例:stackoverflow.com/a/66411954/560942
  • 我查看了代码并确定它会起作用,但问题是我不太了解它。所以我不认为使用它对我来说是最好的主意。但是感谢@jnpdx
  • @jnpdx 你知道我怎样才能让地图跟随大头针吗?所以当前位置总是在地图的中心?

标签: ios swiftui gps location deprecated


【解决方案1】:

是的,它已被弃用,赞成使用同名的属性而不是函数,尝试不带括号...

if manager.authorizationStatus == .authorizedWhenInUse {

【讨论】:

  • 感谢这解决了@Abizern 的错误和警告问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-20
  • 2023-03-03
  • 2021-04-08
  • 1970-01-01
相关资源
最近更新 更多