gpt4 book ai didi

swift - 在 Swift 中同步异步内容

转载 作者:可可西里 更新时间:2023-11-01 01:05:42 28 4
gpt4 key购买 nike

我不确定为什么 Apple 会以 block 的形式设计这么多东西......至少“PHAsset to UIImage”中的问题由于提供的选项而得以解决。但是,选项没有提供我需要的其他一些东西。

例如:

func getAssetUrl(asset: PHAsset) -> NSURL {
var option = PHContentEditingInputRequestOptions()
asset.requestContentEditingInputWithOptions(option, completionHandler: {(contentEditingInput, info) -> Void in
var imageURL = contentEditingInput.fullSizeImageURL
println(imageURL)
})
return NSURL()
}

在这些情况下,我只需要占用一个 block 的函数(例如 requestContentEditingInputWithOptions 同步执行,以便我可以返回 imageURL)。有什么办法吗? (我试过使用一些调度命令,但还没有成功)。

请注意,我需要返回 imageURL。不要试图给我一个解决方案,在该解决方案中我在 block 内写入内容并且不返回 imageURL。

最佳答案

我知道您明确要求不要看到这个答案,但为了 future 的读者,我觉得有必要发布处理异步方法的正确方法,即自己遵循异步模式并使用 completionHandler:

func getAssetUrl(asset: PHAsset, completionHandler: @escaping (URL?) -> Void) {
let option = PHContentEditingInputRequestOptions()
asset.requestContentEditingInput(with: option) { contentEditingInput, _ in
completionHandler(contentEditingInput?.fullSizeImageURL)
}
}

你会像这样使用它:

getAssetUrl(asset) { url in
guard let url = url else { return }

// do something with URL here
}

// anything that was here that needs URL now goes above, inside the `completionHandler` closure

还有其他更复杂的模式(操作、第三方 promises/futures 实现等),但 completionHandler 模式通常可以非常优雅地处理这些情况。

关于swift - 在 Swift 中同步异步内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30852577/

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