Swift - 判斷是否有某功能訪問權限,沒有則提示,並自動跳轉到設置頁
阿新 • • 發佈:2017-07-04
權限 cells key 選擇 href ref options title kit 由於 iOS 系統的安全限制,App 如果需要訪問設備的通訊錄、麥克風、 相冊、 相機、地理位置等時,需要請求用戶是否允許訪問。
有時用戶不小心點了“不允許”,後面可能就不知道要去哪裏再開啟這個權限了。這就要求我們應用在每次調用相關功能的時候先獲取相關的授權狀態,如果還沒授權則彈出授權申請的提示框。如果之前被拒絕了,則彈出相關提示框讓用戶很方便地自動跳轉到設置頁面去修改權限。
原文出自:www.hangge.com 轉載請保留原文鏈接:http://www.hangge.com/blog/cache/detail_1517.html
有時用戶不小心點了“不允許”,後面可能就不知道要去哪裏再開啟這個權限了。這就要求我們應用在每次調用相關功能的時候先獲取相關的授權狀態,如果還沒授權則彈出授權申請的提示框。如果之前被拒絕了,則彈出相關提示框讓用戶很方便地自動跳轉到設置頁面去修改權限。
1,樣例效果圖
(1)這裏以照片的訪問權限為例。為方便演示,我在頁面初始化完畢後就請求權限。 (2)第一次請求的時候我們選擇“不允許”。再次啟動程序時,會提示用戶照片訪問受限,需要授權。 (3)點擊“設置”按鈕後便自動跳轉到系統設置頁面。2,樣例代碼
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 |
import UIKit
import Photos
class ViewController : UIViewController {
override func viewDidLoad() {
_ = authorize()
}
func authorize()-> Bool {
let status = PHPhotoLibrary .authorizationStatus()
switch status {
case .authorized:
return true
case .notDetermined:
// 請求授權
PHPhotoLibrary .requestAuthorization({ (status) -> Void in
DispatchQueue .main.async(execute: { () -> Void in
_ = self .authorize()
})
})
default : ()
DispatchQueue .main.async(execute: { () -> Void in
let alertController = UIAlertController (title: "照片訪問受限" ,
message: "點擊“設置”,允許訪問您的照片" ,
preferredStyle: .alert)
let cancelAction = UIAlertAction (title: "取消" , style: .cancel, handler: nil )
let settingsAction = UIAlertAction (title: "設置" , style: . default , handler: {
(action) -> Void in
let url = URL (string: UIApplicationOpenSettingsURLString )
if let url = url, UIApplication .shared.canOpenURL(url) {
if #available(iOS 10, *) {
UIApplication .shared.open(url, options: [:],
completionHandler: {
(success) in
})
} else {
UIApplication .shared.openURL(url)
}
}
})
alertController.addAction(cancelAction)
alertController.addAction(settingsAction)
self .present(alertController, animated: true , completion: nil )
})
}
return false
}
override func didReceiveMemoryWarning() {
super .didReceiveMemoryWarning()
}
}
|
原文出自:www.hangge.com 轉載請保留原文鏈接:http://www.hangge.com/blog/cache/detail_1517.html
Swift - 判斷是否有某功能訪問權限,沒有則提示,並自動跳轉到設置頁