如何使用 NSItemProvider 的新 Async loadItem 方法加载 URL?

Gil*_*les 1 foundation swift

DropDelegate将文件从桌面拖到我的应用程序时,我很难在 SwiftUI 中获取 fileURL 。

我正在使用异步 loadItem 调用,NSItemProvider该调用返回一个NSSecureCoding. 我以为我可以将结果转换为 NSURL 但它总是失败。

let url = try await (urlProvider
    .loadItem(forTypeIdentifier: UTType.url.identifier) as? NSURL
Run Code Online (Sandbox Code Playgroud)

如果我尝试强制转换,则会出现以下错误:

Could not cast value of type 'Foundation.__NSSwiftData' to 'NSURL'.
Run Code Online (Sandbox Code Playgroud)

我在代码中的其他地方成功地使用了相同的调用并转换为 NSDictionary。

这是在 Xcode 13.4、Swift 5 中。我在沙箱功能中具有对用户选择的文件的读取权限。

谁能帮助指出我做错了什么?谢谢。

Gil*_*les 5

我必须转换Data为然后从中构建URL

if let data = try await urlProvider
    .loadItem(forTypeIdentifier: UTType.fileURL.identifier) as? Data {
    url = URL(dataRepresentation: data, relativeTo: nil) }
Run Code Online (Sandbox Code Playgroud)