我有这个简单的代码用于保存图像:
@IBAction private func saveImageButtonTouch(sender:UIButton) {
let image = areaForImageCaptureView.asImage()
UIImageWriteToSavedPhotosAlbum(image, self, #selector(image(_:didFinishSavingWithError:contextInfo:)), nil)
}
@objc func image(_ image: UIImage, didFinishSavingWithError error: NSError?, contextInfo: UnsafeRawPointer) {
if let error = error {
let alertVC = UIAlertController(title: "Save Error", message: "Could not save image to camera roll", preferredStyle: .alert)
alertVC.addAction(UIAlertAction(title: "Okay", style: .default))
present(alertVC, animated: true)
} else {
// Saved
}
}
如果用户不允许访问,再次点击按钮不会重新提示访问,只是显示相同的错误。
如何打开应用程序的“设置”以允许用户更改其权限?
最好的解决方案是在尝试保存图像之前检查当前将图像添加到照片库的权限。如果权限被拒绝,您可以显示一条警报,通知用户这种情况,并为他们提供打开应用程序设置的选项,以便他们可以根据需要更改权限。
@IBAction private func saveImageButtonTouch(sender:UIButton) {
let status = PHPhotoLibrary.authorizationStatus(for: .addOnly)
switch status {
case .notDetermined:
PHPhotoLibrary.requestAuthorization(for: .addOnly) { [unowned self] status in
if status != .denied {
saveImage()
}
}
case .denied:
let alertVC = UIAlertController(title: "Save Denied", message: "You have denied the ability to save images to your photo library.", preferredStyle: .alert)
alertVC.addAction(UIAlertAction(title: "OK", style: .default))
alertVC.addAction(UIAlertAction(title: "Settings", style: .default) { action in
let url = URL(string: UIApplication.openSettingsURLString)!
UIApplication.shared.open(url)
})
present(alertVC, animated: true)
case .restricted, .authorized, .limited:
saveImage()
@unknown default:
break
}
}
private func saveImage() {
let image = areaForImageCaptureView.asImage()
UIImageWriteToSavedPhotosAlbum(image, self, #selector(image(_:didFinishSavingWithError:contextInfo:)), nil)
}
@objc func image(_ image: UIImage, didFinishSavingWithError error: NSError?, contextInfo: UnsafeRawPointer) {
if error != nil {
let alertVC = UIAlertController(title: "Save Error", message: "Could not save image to camera roll", preferredStyle: .alert)
alertVC.addAction(UIAlertAction(title: "Okay", style: .default))
present(alertVC, animated: true)
} else {
// Saved
}
}
理论上,您可以简单地调用
requestAuthorization(for:)
,而无需先调用 authorizationStatus(for:)
,并处理所有 status
值。但用户体验就不那么好了。这是因为用户第一次运行您的应用程序并点击按钮时,系统将提示用户选择权限。如果他们选择“拒绝”,那么代码将立即提示他们已拒绝许可。但他们知道他们只是否认了这一点。通过进行两次授权调用,您可以更好地控制用户体验。
另一种可能的解决方案是尝试在不进行授权检查的情况下写入图像(就像您现在所做的那样)。如果用户拒绝权限,写入将失败,并且完成处理程序中将出现错误(正如您现在所看到的)。但不幸的是,您收到的错误并没有给出明确指示用户已拒绝权限的错误。如果错误确实给出了这样的指示,您可以处理该特定错误以提示用户转到设置。
请记住,如果用户点击“设置”按钮,他们将被带到应用程序的设置页面。如果用户更改照片权限(或您的应用程序碰巧使用的任何其他隐私权限),则该应用程序将被终止。对于任何权限更改的 iOS 应用程序来说,这是正常现象。如果用户随后返回应用程序,应用程序将完全重新启动,就像用户强制退出应用程序一样。即使用户直接运行“设置”应用程序并更改应用程序的隐私设置,也会看到相同的行为。此行为并非特定于从应用程序内启动应用程序的设置。