这是因为iOS要求应用程序开发者在允许访问相册之前要先获得用户的许可。为此,我们必须在 Info.plist 文件中添加名为 NSPhotoLibraryAddUsageDescription 的键,并为其添加相应的描述:

问题修复完成!再次运行,点击保存按钮,打开相册应用,你会看到刚才保存的二维码:

到目前为止,我们的工作已基本完成,但是为了更完美一些,最好是在点击保存按钮之后能够收到是否保存成功的反馈。所以需要在 saveQRCodeImage 方法中更改 UIImageWriteToSavedPhotosAlbum 函数的参数:
- (void)saveQRCodeImage
{
...
// 保存图像
UIImageWriteToSavedPhotosAlbum(self.imageView.image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
}
然后添加 image:didFinishSavingWithError:contextInfo: 方法,并在该方法内创建alert View来显示二维码的保存状态:
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
NSString *title;
NSString *message;
if (!error) {
message = @"The QRCode image saved successfully.";
}
else {
message = @"The QRCode image saved unsuccessfully, please try again later.";
}
// 使用alert view显示二维码保存状态
UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *action = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil];
[alert addAction:action];
[self presentViewController:alert animated:YES completion:nil];
}
运行程序,测试一下效果:

至此,我们的二维码生成器已经全部完成,如果需要完整代码,可以下载 QRCodeGeneratorDemo 查看。
3 参考资料
CIFilter - Core Image | Apple Developer Documentation
Building a QR Code Generator with Core Image Filters
CIQRCodeGenerator
HOW TO SAVE/LOAD IMAGE/VIDEOS FROM CAMERA ROLL – XCODE IOS
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持ASPKU。
注:相关教程知识阅读请移步到IOS开发频道。










