简体   繁体   English

Swift - 使用异步方法加载 PHPickerResult

[英]Swift - Using Async Method to Load PHPickerResult

I am trying to load a user selected image from photos using PHPickerViewController's delegate method.我正在尝试使用 PHPickerViewController 的委托方法从照片中加载用户选择的图像。 I know that I can do that with result.itemProvider.loadObject;我知道我可以用 result.itemProvider.loadObject 做到这一点; however, I want to use an async version of that method that does not require a completion handler.但是,我想使用不需要完成处理程序的该方法的异步版本。 This is what I tried:这是我尝试过的:

func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
    Task {
        do {
            for result in results {
                let x = try await result.itemProvider.loadItem(forTypeIdentifier: String(describing: UIImage.self)) as? UIImage
            }
        } catch {
            print("parsing_error")
        }
    }
}

I am getting a parsing error.我收到解析错误。 To be honest, I'm not sure how itemProvider.loadItem works exactly, and I've had trouble finding much info on it.老实说,我不确定 itemProvider.loadItem 是如何工作的,而且我很难找到很多关于它的信息。 Any recommendations?有什么建议吗?

I don't know why your code doesn't work.我不知道为什么你的代码不起作用。 (It doesn't work for me either, for what it's worth.) However, I did determine code that does work, although you might not consider it to be an improvement over just using loadObject with a callback: (它对我也不起作用,因为它的价值。)但是,我确实确定了有效的代码,尽管您可能不认为它是对仅使用带有回调的 loadObject 的改进:

Task {
    do {
        let url = try await item.loadItem(forTypeIdentifier: "public.image") as! URL
        let data = try Data(contentsOf: url)
        if let image = UIImage(data: data) {
            print("Image loaded: \(image)")
        } else {
            print("Error loading image!");
        }
    } catch let error {
        print("async loadItem failed: \(error)")
    }
}

Note: I tried to use UIImage(contentsOfFile: url.absoluteString) instead of loading the URL into a Data object and then loading the UIImage from that. Note: I tried to use UIImage(contentsOfFile: url.absoluteString) instead of loading the URL into a Data object and then loading the UIImage from that. That didn't work, and I don't know why.那没有用,我不知道为什么。 All I know is that UIImage(contentsOfFile:) returned nil.我所知道的是UIImage(contentsOfFile:)返回 nil。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM