D.Jacob
D.Jacob

Reputation: 1

Location services permission keeps disappearing

I am working on an app which will display points of interest on a map around the users location. The problem is, when the app loads, the permission dialog disappears instantly before the user can allow or deny permissions.

My code looks like this:

override func viewDidLoad() {
    super.viewDidLoad()

    logo.animation = "zoomIn"
    logo.duration = 1
    logo.delay = 0.5
    logo.animate()

    formatView()

    let locationManager = CLLocationManager()
    let authStatus: CLAuthorizationStatus = CLLocationManager.authorizationStatus()

    if authStatus == .notDetermined {
        locationManager.requestWhenInUseAuthorization()
    }

    if authStatus == .denied || authStatus == .restricted {
        showLocationServicesDeniedAlert()
        return
    }
}

But I have no idea what I'm doing wrong. Ive tried to follow other answers on here for similar problems but it seems like there are a few reasons this can happen and I have no idea which one my problem is I'm tearing hairs out!

Upvotes: 0

Views: 531

Answers (2)

vacawama
vacawama

Reputation: 154691

You are assigning locationManager to a local variable of viewDidLoad which gets released immediately when viewDidLoad finishes. Instead, make locationManager a property of your ViewController:

var locationManager: CLLocationManager?

override func viewDidLoad() {
    ...

    locationManager = CLLocationManager()

    ...
}

Upvotes: 1

Muhammad Abdul Subhan
Muhammad Abdul Subhan

Reputation: 436

Try moving the the code in viewWillAppear as requestWhenInUseAuthorization needs to be called when view controller has appeared. And you could study the View Controller Life Cycle here to know more about their appearance, loading and everything.

Upvotes: 0

Related Questions