Search code examples
swiftswiftuiapple-watch

Cannot request for location permission on Apple Watch


Updated:

I created a small Xcode project https://github.com/gie3d/getting-location-permission-problem. Incase anyone would like to try on this problem.


I'm developing an app for Apple Watch. The app needs to access user location. The problem is when I request a location permission, the request permission sheet doesn't show. Even though the authorizationStatus is .notDetermined

My code

import Foundation
import CoreLocation

class WorkoutManager: NSObject, ObservableObject {
  let locationManager = CLLocationManager()

  func requestLocationAuthorization() {
        print("prepare to request location permission")
        locationManager.requestWhenInUseAuthorization()
        if CLLocationManager.locationServicesEnabled() {
            
            print("it is enabled")
            switch locationManager.authorizationStatus {
                case .notDetermined:
                    print("not determined")
                case .restricted:
                    print("restricted")
                case .denied:
                    print("denied")
                case .authorizedAlways, .authorizedWhenInUse:
                    print("Access")
            }
        } else {
            print("it is not enabled")
        }
    }
}

I passed this WorkoutManager into my SwiftUI View using an environment object

import SwiftUI

@main
struct RunnerApp: App {
    @StateObject var workoutManager = WorkoutManager()
    @SceneBuilder var body: some Scene {
        WindowGroup {
            NavigationView {
                ContentView()
            }
            .environmentObject(workoutManager)
        }
    }
}

And this is my ContentView, I called requestLocationAuthorization() during onAppear()

import SwiftUI

struct ContentView: View {
    
    @EnvironmentObject var workoutManager: WorkoutManager
    var body: some View {
        ScrollView {
            Text("Hello World")
        }
        .navigationBarTitleDisplayMode(.inline)
        .navigationTitle("Test")
        .onAppear() {
            print("on appear - content view")
            workoutManager.requestLocationAuthorization()
        }
    }
}

And the output log shows as below...

on appear - content view
prepare to request location permission
it is enabled
not determined

I wonder if the location permission is still not determined, why requestWhenInUseAuthorization() did nothing?


Solution

  • I think I misunderstood with the concept of Apple Watch as a standalone app and a companion app.

    At the Deployment Info, if the "Supports Running Without iOS App Installation doesn't check, the user will have to grant location permission from the companion iOS app. But if it's checked, the location permission request will show up when the user opens the app.

    enter image description here