当用户点击该按钮时,它会在询问用户许可之前立即触发“已保存照片”警报。如果用户单击“否”,则照片将不会保存,但仍会显示警报。在用户允许访问照片库之前,我是否可以使用if else语句来使其没有警报弹出窗口?
@IBAction func savePhotoClicked(_ sender: Any) {
UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)
let alert = UIAlertController(title: "Saved!", message: "This wallpaper has been saved.", preferredStyle: .alert)
let okAction = UIAlertAction(title: "Ok", style: .default, handler: nil)
alert.addAction(okAction)
self.present(alert, animated: true, completion: nil)
}
您过早地显示警报控制器的方式。对UIImageWriteToSavedPhotosAlbum
的调用是异步的。查看您传递给第2,第3和第4参数的所有nil
值?用适当的值替换那些,以便在UIImageWriteToSavedPhotosAlbum
的调用实际完成时调用警报,并且可以正确地确定图像是否实际保存。
@IBAction func savePhotoClicked(_ sender: Any) {
UIImageWriteToSavedPhotosAlbum(image, self, #selector(image(_:didFinishSavingWithError:contextInfo:)), nil)
}
@objc func image(_ image: UIImage, didFinishSavingWithError error: Error?, contextInfo: UnsafeRawPointer) {
if let error = error {
// show error
} else {
let alert = UIAlertController(title: "Saved!", message: "This wallpaper has been saved.", preferredStyle: .alert)
let okAction = UIAlertAction(title: "Ok", style: .default, handler: nil)
alert.addAction(okAction)
self.present(alert, animated: true, completion: nil)
}
}
让我们在做任何事之前检查+authorizationStatus
(类PHPhotoLibrary
)的值。如果状态为+requestAuthorization
,您还可以使用PHAuthorizationStatus.notDetermined
方法请求访问Photo Library
更多信息:PHPhotoLibrary authorizationStatus,PHPhotoLibrary requestAuthorization
通常:
nil
作为两个参数UIImageWriteToSavedPhotosAlbum
函数的类,所以completionTarget
通常是self
正如文档所述,completionSelector
是一个表示具有文档中描述的签名的方法的选择器,因此它必须具有如下签名:
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo: (void *) contextInfo;
它不必具有这个确切的名称,但它必须使用相同的签名,即取3个参数(第一个是UIImage
,第二个是NSError
,第三个是void*
类型)并且什么都不返回(void
)。
例如,您可以声明并实现一个可以调用此方法的方法:
- (void)thisImage:(UIImage *)image hasBeenSavedInPhotoAlbumWithError:(NSError *)error usingContextInfo:(void*)ctxInfo {
if (error) {
// Do anything needed to handle the error or display it to the user
} else {
// .... do anything you want here to handle
// .... when the image has been saved in the photo album
}
}
当你打电话给UIImageWriteToSavedPhotosAlbum
时,你会像这样使用它:
UIImageWriteToSavedPhotosAlbum(theImage,
self, // send the message to 'self' when calling the callback
@selector(thisImage:hasBeenSavedInPhotoAlbumWithError:usingContextInfo:), // the selector to tell the method to call on completion
NULL); // you generally won't need a contextInfo here
请注意@selector(...)
语法中的多个':'。冒号是方法名称的一部分,所以当你写这行时,不要忘记在@selector中添加这些':'(事件是训练一个)!