当用户单击按钮时,它会立即触发“照片已保存”警报,然后再询问用户许可。如果用户单击“否”,则照片将不会保存,但警报仍会显示。在用户允许访问照片库之前,是否有if语句可以使我弹出警告?
@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)
}
答案 0 :(得分:2)
您过早显示警报控制器。对UIImageWriteToSavedPhotosAlbum
的调用是异步的。查看您要传递给第二,第三和第四参数的所有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)
}
}
答案 1 :(得分:0)
在执行任何操作之前,请检查+authorizationStatus
(类PHPhotoLibrary
)的值。如果状态为+requestAuthorization
PHAuthorizationStatus.notDetermined
访问照片库
更多信息:PHPhotoLibrary authorizationStatus,PHPhotoLibrary requestAuthorization
答案 2 :(得分:0)
通常:
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中添加这些':'(事件为训练)!