Mercutio
Mercutio

Reputation: 1296

CoreLocation requestWhenInUseAuthorization flashes for a second and then disappears, or just doesn't show

I'm trying to get my simulator setup to approve core location. A few times I've had the permission window actually pop up, but it quickly disappeared before I could select the "While In-Use" option.

I've tried the following based off of other similar questions I saw here and wenderlich walkthrough...

  1. Features > Location > Apple
  2. Info Plist has entries for... enter image description here
  3. Delete the app and:

Settings > General > Reset > Reset Location & Privacy

Using the below code on Xcode 12.4, Swift 5.1, iPhone SE - 2nd generation - iOS 14.4 simulator...

import SwiftUI
import CoreLocation

struct ContentView: View {

    @Environment(\.managedObjectContext) private var viewContext

    func setupCL() {
        let locationManager = CLLocationManager()
        let clDelegate = CLDelegate()
        locationManager.delegate = clDelegate
        if locationManager.authorizationStatus == .notDetermined {
            locationManager.requestWhenInUseAuthorization()
        }
    }

    var body: some View {
        Button(action: {setupCL()}, label: {
            Text("Button")
        })
    }
}

class CLDelegate: NSObject, CLLocationManagerDelegate { }

What am I missing?

Upvotes: 0

Views: 292

Answers (1)

jnpdx
jnpdx

Reputation: 52387

Your locationManager and delegate are immediately going out of scope because you're calling them in a function on the view and not retaining them anywhere. Moving them to an ObservableObject makes everything work:


class Manager : ObservableObject {
    let locationManager = CLLocationManager()
    let clDelegate = CLDelegate()
    
    func setupCL() {
        locationManager.delegate = clDelegate
        if locationManager.authorizationStatus == .notDetermined {
            locationManager.requestWhenInUseAuthorization()
        }
    }
}

struct ContentView: View {

   @StateObject private var manager = Manager()

    var body: some View {
        Button(action: {manager.setupCL()}) {
            Text("Button")
        }
    }
}

Upvotes: 1

Related Questions