gpt4 book ai didi

swift3 - 第一次运行时在自定义相册中保存照片失败

转载 作者:行者123 更新时间:2023-12-01 12:22:57 25 4
gpt4 key购买 nike

您好,我正在创建一个相册应用程序作为一个学习项目,我在使用 PHPhotoLibrary.shared().performChangesAndWait 时遇到了一些问题;主要问题是,当方法 saveImage 具有 PHPhotoLibrary.shared().performChangesAndWait 代码时;该方法在 PHPhotoLibrary.shared().performChangesAndWait 完成保存图像之前退出。似乎代码会异步执行,即使我正在使用 performChangesAndWait 方法,根据文档说它应该等到它完成。

这是我的类中 saveImage 方法的代码:

func saveImage(_ image: UIImage) ->Bool {
print("Executing saveImage")
var result:Bool = false
if assetCollection == nil {
print("the album is nil")
return result
}
print("saveImage: we will start saving the image")
//TODO: the return false is happening before the photo is save.
do
{
try PHPhotoLibrary.shared().performChangesAndWait({
let assetChangeRequest = PHAssetChangeRequest.creationRequestForAsset(from: image)
let assetPlaceHolder = assetChangeRequest.placeholderForCreatedAsset
let albumChangeRequest = PHAssetCollectionChangeRequest(for: self.assetCollection)
let enumeration: NSArray = [assetPlaceHolder!]
albumChangeRequest!.addAssets(enumeration)
print("saveImage: image was save without issues")
result = true
print("saveImage: result value after saving the image: \(result)")
})
}
catch let error
{
result = false
print("saveImage: there was a problem: \(error.localizedDescription)")
}


print("saveImage: result value before exiting the method: \(result)")
return result

}

基本上,当应用程序第一次运行时,返回结果在保存图像 block 完成之前得到执行。

有什么方法可以强制 saveImage 方法实际等待 performChangesAndWait 方法实际完成?

预先感谢您的帮助。

最佳答案

performChangesAndWait 是一个异步回调方法。在 performChangesAndWait 中对 result 所做的更改不会反射(reflect)在 return 上,因为这两个在不同的线程中。

等待saveImage 方法完成的一种方法是实现回调。像这样的东西:

func saveImage(_ image: UIImage, callback: @escaping(_ result: Bool)->Void) {
print("Executing saveImage")

if assetCollection == nil {
print("the album is nil")
callback(false)
}
print("saveImage: we will start saving the image")
//TODO: the return false is happening before the photo is save.
do {
try PHPhotoLibrary.shared().performChangesAndWait({
let assetChangeRequest = PHAssetChangeRequest.creationRequestForAsset(from: image)
let assetPlaceHolder = assetChangeRequest.placeholderForCreatedAsset
let albumChangeRequest = PHAssetCollectionChangeRequest(for: self.assetCollection)
let enumeration: NSArray = [assetPlaceHolder!]
albumChangeRequest!.addAssets(enumeration)
print("saveImage: image was save without issues")

callback(true)
})
}
catch let error {
print("saveImage: there was a problem: \(error.localizedDescription)")
callback(false)
}
}

让我们知道您得到了什么。

关于swift3 - 第一次运行时在自定义相册中保存照片失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42312273/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com