尝试制作具有iPhone各种权限的快速文件,包括
所以我尝试搜索 如何知道用户是否有权使用Camera ?
,并且大多数情况下是通过Switch statements
获得功能。我要寻找的是在项目中任何地方调用函数的通用函数:例如,在情况.authorised
然后执行代码A elseif
的情况下,我想执行的项目其他位置的调用。拒绝然后再执行代码B其他.notDetermined
则执行C。
func checkPhotoLibraryPermission() {
let status = PHPhotoLibrary.authorizationStatus()
switch status {
case .authorized:
print("Authorized")
case .denied, .restricted :
case .notDetermined:
PHPhotoLibrary.requestAuthorization() { status in
switch status {
case .authorized:
print("Authorized")
case .denied, .restricted:
print("No access")
case .notDetermined:
print("Not determined")
}
}
}
}
答案 0 :(得分:2)
您需要一个回调函数,因为PHPhotoLibrary.requestAuthorization()
是异步操作。
func checkPhotoLibraryPermission(callback:(authorized:Bool)->Void) {
let status = PHPhotoLibrary.authorizationStatus()
switch status {
case .authorized:
callback(true)
case .denied, .restricted :
callback(false)
case .notDetermined:
PHPhotoLibrary.requestAuthorization() { status in
switch status {
case .authorized:
callback(true)
case .denied, .restricted,.notDetermined:
callback(false)
}
}
}
}
答案 1 :(得分:1)
是的,您可以在块的帮助下完成此操作。
public typealias CompletionHandler = ((Bool)->Void)?
@objc func yourMethod(completionBlock : CompletionHandler){
let status = PHPhotoLibrary.authorizationStatus()
switch status {
case .authorized:
completionBlock(true);
case .denied, .restricted :
completionBlock(false);
case .notDetermined:
PHPhotoLibrary.requestAuthorization() { status in
switch status {
case .authorized:
completionBlock(true);
case .denied, .restricted:
completionBlock(false);
case .notDetermined:
completionBlock(false);
}
}
}
}
这只是您可以相应编写的示例。
答案 2 :(得分:0)
使用返回类型更新功能
func isPhotoLibraryPermission() -> bool {
let status = PHPhotoLibrary.authorizationStatus()
switch status {
case .authorized:
print("Authorized")
return true
case .denied, .restricted :
return false
case .notDetermined:
PHPhotoLibrary.requestAuthorization() { status in
switch status {
case .authorized:
print("Authorized")
return true
case .denied, .restricted:
print("No access")
return false
case .notDetermined:
print("Not determined")
return false
}
}
}
}
PS:如果您需要更通用的东西,请为所有要返回的情况创建枚举,然后返回:-)
答案 3 :(得分:0)
func checkPhotoLibraryPermission() -> Bool {
let status = PHPhotoLibrary.authorizationStatus()
switch status {
case .authorized:
print("Authorized")
return true
case .denied:
return true
case .restricted :
return false
case .notDetermined:
return false
}
}
}
类似这样的东西?如果是的话,那就太好了;如果没有,那就让我知道你到底想要什么,所以我可以根据您的要求尝试编码开关盒:)