3

我不确定为什么 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。

4

1 回答 1

3

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

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

于 2015-06-15T19:00:51.387 回答