且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 SwiftUI 中获取已删除文件的文件名?

更新时间:2022-02-04 16:08:39

在 apis 上花费了一个多小时(文档几乎不存在),以下是对我有用的方法:

Having spent more than an hour struggling with the apis (the documentation is almost nonexistent), here is what worked for me:

// The onDrop registration
.onDrop(of: [(kUTTypeFileURL as String)], delegate: self)

...

func performDrop(info: DropInfo) -> Bool {

    guard let itemProvider = info.itemProviders(for: [(kUTTypeFileURL as String)]).first else { return false }

    itemProvider.loadItem(forTypeIdentifier: (kUTTypeFileURL as String), options: nil) {item, error in
        guard let data = item as? Data, let url = URL(dataRepresentation: data, relativeTo: nil) else { return }
        // Do something with the file url
        // remember to dispatch on main in case of a @State change
    }

    return true
}

请注意,我省略了任何验证,因此此代码从任何已删除的文件中获取第一个 url

Please note that I have omitted any validation, so this code grabs the first url from any dropped files