在 SwiftUI 中请求用户位置权限 [英] Request User Location Permission In SwiftUI

查看:77
本文介绍了在 SwiftUI 中请求用户位置权限的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 SwiftUI 中获取用户位置权限?

How do you get user location permissions in SwiftUI?

我尝试在点击按钮后请求用户位置权限,但对话框在大约一秒钟后消失.即使你最终及时点击了它,权限仍然被拒绝.

I tried asking for user location permissions after a button tap, but the dialogue box disappears after about a second. Even if you do end up clicking it in time, permission is still denied.

import CoreLocation
.
.
.
Button(action: {
    let locationManager = CLLocationManager()
    locationManager.requestAlwaysAuthorization()
    locationManager.requestWhenInUseAuthorization()
}) {
    Image("button_image")
}

推荐答案

诸如位置管理器之类的东西应该在您的模型中,而不是您的视图中.

Things like location manager should be in your model, not your view.

然后您可以调用模型上的函数来请求位置权限.

You can then invoke a function on your model to request location permission.

你现在所做的问题是你的 CLLocationManager 在关闭完成后立即被释放.权限请求方法异步执行,因此关闭很快结束.

The problem with what you are doing now is that your CLLocationManager gets released as soon as the closure is done. The permission request methods execute asynchronously so the closure ends very quickly.

释放位置管理器实例后,权限对话框消失.

When the location manager instance is released the permission dialog disappears.

位置模型可能如下所示:

A location model could look something like this:

class LocationModel: NSObject, ObservableObject {
    private let locationManager = CLLocationManager()
    @Published var authorisationStatus: CLAuthorizationStatus = .notDetermined

    override init() {
        super.init()
        self.locationManager.delegate = self
    }

    public func requestAuthorisation(always: Bool = false) {
        if always {
            self.locationManager.requestAlwaysAuthorization()
        } else {
            self.locationManager.requestWhenInUseAuthorization()
        }
    }
}

extension LocationModel: CLLocationManagerDelegate {

    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
        self.authorisationStatus = status
    }
}

您可能还希望函数启动 &停止位置更新和 @Published CLLocation 属性

You would probably also want functions to start & stop location updates and an @Published CLLocation property

这篇关于在 SwiftUI 中请求用户位置权限的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆