Search code examples
iosswiftuigpslocationdeprecated

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

if CLLocationManager.authorizationStatus() == .authorizedWhenInUse{

I get this warning

'authorizationStatus()' was deprecated in iOS 14.0

I tried looking at other stackoverflow posts but I don't really get it. 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")
    }
}

Solution

  • Yes, it's been deprecated in favour of using a property of the same name instead of a function, try it without the parentheses...

    if manager.authorizationStatus == .authorizedWhenInUse {