我想使用以下的void API将捕获的图像写入相册,但我不太清楚其中的2个参数
UIImageWriteToSavedPhotosAlbum (
UIImage *image,
id completionTarget,
SEL completionSelector,
void *contextInfo
);
Run Code Online (Sandbox Code Playgroud)
从ADC的解释:
completionTarget:可选的; 在将图像写入相机胶卷相册后应调用其选择器的对象.
completionSelector:completionTarget对象的方法选择器.此可选方法应符合以下签名:
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo: (void *) contextInfo;
Run Code Online (Sandbox Code Playgroud)
completionTarget这里有什么意义?有人可以用一个例子来解释如何使用这个参数吗?或任何可以指导我完成它的资源.
Ali*_*are 110
completionSelector是选择器(方法)当所述图像的写入已完成呼叫.completionTarget是在其上调用此方法的对象.通常:
nil这两个参数UIImageWriteToSavedPhotosAlbum函数的类,所以completionTarget一般都是self正如文档所述,completionSelector是一个选择器,表示具有文档中描述的签名的方法,因此它必须具有如下签名:
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo: (void *) contextInfo;
Run Code Online (Sandbox Code Playgroud)
它不必具有这个确切的名称,但它必须使用相同的签名,即取3个参数(第一个是a 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
}
}
Run Code Online (Sandbox Code Playgroud)
当你打电话时,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
Run Code Online (Sandbox Code Playgroud)
请注意@selector(...)语法中的多个':' .冒号是方法名称的一部分,所以当你写这行时,不要忘记在@selector中添加这些':'(事件是训练一个)!
在现代 iOS 中,使用 UIImageWriteToSavedPhotosAlbum 有一个额外的要求。您必须在Info.plist中包含一个密钥NSPhotoLibraryAddUsageDescription(“隐私 - 照片库添加使用说明”)。这样系统就可以向用户呈现一个对话框,请求写入相机胶卷的权限。
然后,您可以在代码中调用 UIImageWriteToSavedPhotosAlbum:
func myFunc() {
let im = UIImage(named:"smiley.jpg")!
UIImageWriteToSavedPhotosAlbum(im, self, #selector(savedImage), nil)
}
Run Code Online (Sandbox Code Playgroud)
最后一个参数,上下文,通常是nil。
self后两个参数和的想法#selector(savedImage)是,您的savedImage方法self将在图像保存(或不保存)后回调。该方法应该如下所示:
@objc func savedImage(_ im:UIImage, error:Error?, context:UnsafeMutableRawPointer?) {
if let err = error {
print(err)
return
}
print("success")
}
Run Code Online (Sandbox Code Playgroud)
典型的错误是用户在系统对话框中拒绝权限。如果一切顺利,将会出现错误nil,您就会知道写入成功。
一般来说,应该避免使用 UIImageWriteToSavedPhotosAlbum,而使用照片框架。然而,这是完成工作的简单方法。
| 归档时间: |
|
| 查看次数: |
37699 次 |
| 最近记录: |