在Swift中同步Async Stuff

时间:2015-06-15 18:36:41

标签: swift phasset

我不确定为什么Apple会在块中设计这么多东西...... 至少由于提供的选项,“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()
}

在这些情况下,我只想要一个带块的函数(比如requestContentEditingInputWithOptions同步执行,所以我可以返回imageURL)。有没有办法做到这一点? (我尝试过使用一些调度命令,但还没有成功)。

请注意,我需要返回imageURL。不要试图给我一个解决方案,我在其中写东西并且不返回imageURL。

1 个答案:

答案 0 :(得分:3)

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

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

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