簡體   English   中英

用戶拒絕定位服務后再次請求權限?

[英]Request permissions again after user denies location services?

我跟蹤用戶的位置並在我的負載首次加載時請求許可:

locationManager.requestAlwaysAuthorization()
locationManager.startUpdatingLocation()

如果用戶拒絕,但后來通過啟用我的應用程序中的配置選項改變了主意,我該如何再次詢問? 例如,我有一個用於自動檢測用戶位置的開關,所以當他們啟用它時,我正在嘗試這樣做:

@IBAction func gpsChanged(sender: UISwitch) {
    // Request permission for auto geolocation if applicable
    if sender.on {
        locationManager.requestAlwaysAuthorization()
        locationManager.startUpdatingLocation()
    }
}

但是這段代碼似乎沒有做任何事情。 我希望它會再次詢問用戶是否要允許應用程序跟蹤用戶的位置。 這可能嗎?

操作系統只會提示用戶一次。 如果他們拒絕許可,就是這樣。 可以做的是通過將UIApplicationOpenSettingsURLString傳遞給UIApplicationopenURL:方法將用戶定向到您的應用程序的設置。 如果他們願意,他們可以從那里重新啟用定位服務。 也就是說,您可能不應該過於激進地對他們進行竊聽以獲得許可。

權限彈窗只顯示一次 所以我們必須在那之后將用戶重定向到設置 下面是 Swift 中的代碼:

 import CoreLocation 

 // ...

 @IBAction func userDidClickButton(_ sender: Any) {
   
    // initialise a pop up for using later
    let alertController = UIAlertController(title: "TITLE", message: "Please go to Settings and turn on the permissions", preferredStyle: .alert)

    let settingsAction = UIAlertAction(title: "Settings", style: .default) { (_) -> Void in
        guard let settingsUrl = URL(string: UIApplicationOpenSettingsURLString) else {
            return
        }
        if UIApplication.shared.canOpenURL(settingsUrl) {
            UIApplication.shared.open(settingsUrl, completionHandler: { (success) in })
         }
    }
    let cancelAction = UIAlertAction(title: "Cancel", style: .default, handler: nil)

    alertController.addAction(cancelAction)
    alertController.addAction(settingsAction)

    // check the permission status
    switch(CLLocationManager.authorizationStatus()) {
        case .authorizedAlways, .authorizedWhenInUse:
            print("Authorize.")
            // get the user location
        case .notDetermined, .restricted, .denied:
            // redirect the users to settings
            self.present(alertController, animated: true, completion: nil)
    }
}

你可以有一個替代的解決方案! 您可以使用更好的消息顯示您自己的警報,這可以說服您的用戶允許接收您的應用程序的推送通知。 如果用戶允許,則只有您顯示默認權限警報以啟用推送通知,否則如果用戶不允許,則實際上不顯示默認警報,您可以將相應的標志保存在您的數據庫或 NSUserDefaults 中,並且可以在以后一次又一次地詢問用戶您的應用程序中的一些事件。

你只有一次機會。 要讓用戶在拒絕權限后啟用權限,他們必須通過“設置”應用程序。 請參閱在CLLocationManager中請求使用位置服務的權限。

我創建了包含用於通知的權限管理器的庫,即使在用戶拒絕權限后也會處理權限警報。

https://github.com/CrazyPro007/PermissionManager/tree/master/PermissionManager/PermissionManager

對於 Health Kit api。 開發人員可以簡單地在readTypes Set<HKObjectType>中添加另一個權限,用戶將被重新提示允許權限。 我不完全確定這是否與位置服務相同。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM