locationManager.requestWhenInUseAuthorization()
在用户按下按钮但不显示任何提示时调用.
以下是我的完整代码
import SwiftUI
import CoreLocation
struct ContentView: View {
@ObservedObject var distanceTracker = DistanceTracker();
var body: some View {
Button(action: distanceTracker.enableLocServices){
Text("Enable Location")
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
import CoreLocation
class DistanceTracker: NSObject, ObservableObject, CLLocationManagerDelegate {
let locationManager = CLLocationManager()
var startLocation: CLLocation!
var lastLocation: CLLocation!
@Published var traveledDistance = 0.0
override init() {
super.init()
locationManager.delegate = self
}
func enableLocServices(){
locationManager.requestWhenInUseAuthorization()
print("bruh")
}
func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {
switch manager.authorizationStatus {
case .notDetermined:
print("Location permission not asked for yet")
case .restricted:
print("Location usage is restricted (perhaps by parental controls or some other restriction)")
case .denied:
print("Location permission denied by user")
case .authorizedAlways:
print("Location permission granted for background and foreground use")
case .authorizedWhenInUse:
print("Location permission granted for foreground use only")
@unknown default:
print("An unknown authorization status received")
}
}
}
按下按钮时,它会打印"breh".编辑:另外,打印的状态是"尚未请求位置权限"
NSLocationAlwaysAndWhenInUseUsageDescription
and NSLocationWhenInUseUsageDescription
are both added to the info section.
手表和手机上的定位服务都已启用(这是一款仅限WatchOS的应用程序,但无论如何,我无法让它在iOS上运行),而且之前的许可并未被拒绝.我怎么才能解决这个问题呢?谢谢!