在更改照片库时检测用户何时点击“不允许”

Detect when user tapped Don't Allow when making changes to photo library

当您想对 PHAsset 进行更改时,您可以将其包装在 performChanges 块中。您在完成块中获得成功 Bool 和错误 NSError。现在我想在请求失败的情况下向用户显示警报。这就是诀窍:

PHPhotoLibrary.sharedPhotoLibrary().performChanges({ () -> Void in
    let request = PHAssetChangeRequest(forAsset: asset)
    request.creationDate = date
}, completionHandler: { (success: Bool, error: NSError?) -> Void in
    dispatch_async(dispatch_get_main_queue()) {
        if let error = error {
            //present alert
        }
    }
})

问题是当用户点击“不允许”时它也会显示警报。我不想那样做,用户故意取消它所以没有必要通知他们它失败了​​。但是我怎样才能检测到发生了什么?错误 userInfonil,它似乎没有提供任何有用的信息来检测这种情况。我错过了什么吗?

[PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus 状态){

 NSLog(@"%ld",(long)status);

switch (status) {

    case PHAuthorizationStatusAuthorized:

        // code for display photos


          NSLog(@"ffefwfwfwef");

    case PHAuthorizationStatusRestricted:



        break;
    case PHAuthorizationStatusDenied:

       //code for Dont Allow code

        break;
    default:
        break;
}

}];

现在可以通过检查 error 是否为 PHPhotosError 来实现,如果是,则检查其 code 以查看其是否为 .userCancelled

PHPhotoLibrary.shared().performChanges({
    let request = PHAssetChangeRequest(forAsset: asset)
    request.creationDate = date
}) { success, error in
    guard let error = error else { return }
    guard (error as? PHPhotosError)?.code != .userCancelled else { return }
    
    DispatchQueue.main.async {
        //present alert
    }
}