在用户允许照片库权限之前弹出“已保存的照片”警告?

问题描述 投票:1回答:3

当用户点击该按钮时,它会在询问用户许可之前立即触发“已保存照片”警报。如果用户单击“否”,则照片将不会保存,但仍会显示警报。在用户允许访问照片库之前,我是否可以使用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)


}
ios swift photo
3个回答
2
投票

您过早地显示警报控制器的方式。对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)
    }
}

0
投票

让我们在做任何事之前检查+authorizationStatus(类PHPhotoLibrary)的值。如果状态为+requestAuthorization,您还可以使用PHAuthorizationStatus.notDetermined方法请求访问Photo Library

更多信息:PHPhotoLibrary authorizationStatusPHPhotoLibrary requestAuthorization


0
投票

通常:

  • 要么在图像写入完成时不需要通知(在许多情况下没有用),所以你使用nil作为两个参数
  • 或者你真的希望在图像文件写入相册时得到通知(或者最终出现写入错误),在这种情况下,你通常会在同一个文件中实现回调(=完成时调用的方法)你称之为UIImageWriteToSavedPhotosAlbum函数的类,所以completionTarget通常是self

正如文档所述,completionSelector是一个表示具有文档中描述的签名的方法的选择器,因此它必须具有如下签名:

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo: (void *) contextInfo;

它不必具有这个确切的名称,但它必须使用相同的签名,即取3个参数(第一个是UIImage,第二个是NSError,第三个是void*类型)并且什么都不返回(void)。


Example

例如,您可以声明并实现一个可以调用此方法的方法:

- (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中添加这些':'(事件是训练一个)!

© www.soinside.com 2019 - 2024. All rights reserved.