当我打电话时requestWhenInUseAuthorization()
从 Watch 应用程序中,位置服务提示永远不会向用户显示:无论是在 Watch 应用程序中,还是在 iPhone 应用程序中。
- The 支持无需安装iOS应用程序即可运行未选中(如果我选中它,提示会正确显示,但我不希望我的应用程序在没有 iOS 配套应用程序的情况下运行)。
- 我添加了
NSLocationWhenInUseUsageDescription
键入 iPhone 应用程序和 Watch Extension 的 info.plist。
- 我还尝试在后台模式下添加位置服务(适用于 iPhone 和 Watch Extension)。
怎样才能让手表上显示提示呢?这可能吗?我不一定要要求我的用户打开他们的 iPhone 应用程序来管理应用程序中的请求位置。
import SwiftUI
import CoreLocation
struct ContentView: View {
@StateObject var watchLocationManager = WatchLocManager()
var body: some View {
Button("Request location") { watchLocationManager.requestAuthorization() }
.onAppear {
watchLocationManager.setupLocationManager()
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
class WatchLocManager: NSObject, ObservableObject {
private var locationManager = CLLocationManager()
func setupLocationManager() {
self.locationManager.delegate = self
self.locationManager.activityType = .otherNavigation
self.locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
self.locationManager.distanceFilter = 20.0
}
func requestAuthorization() {
self.locationManager.requestWhenInUseAuthorization()
}
}
extension WatchLocManager: CLLocationManagerDelegate {
func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {
print("⌚️ locationManagerDidChangeAuthorization: \(manager.authorizationStatus.rawValue)")
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
print(locations)
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print(error)
}
}
iPhone 和 Watch 共享“隐私”>“位置服务设置”。如果应用程序已在 iPhone 上具有授权状态,则不会在 Watch 上再次询问。
设置“设置”>“隐私”>“位置服务”>“您的应用”>“允许位置访问”>“下次询问”。
然后打开手表应用程序。
要求的步骤
新项目>WatchOS>带有 WatchApp 的 iOS 应用程序
填写产品名称,其他无变化
保存在 Mac 文件夹中
已更换struct ContentView
& struct ContentView_Previews
用你的代码。
The ContentView.swift
文件位于AppName
folder.
添加到上述文件的Target Membership
the AppName WatchKit Extension
。我在File Inspector
通过选中该框。
去了ContentView.swift
文件位于AppName WatchKit Extension
文件夹并删除(取消选中)文件的Target Membership
to AppName WatchKit Extension
。 (如果不这样做,您将得到一个副本)
Added NSLocationWhenInUseUsageDescription
to Info.plist
在下面AppName WatchKit Extension
Folder.
确信AppName WatchKit App
方案被选定。
按下播放键。等到加载完成...
按下“请求位置”按钮
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)