如何在 SwiftUI 中获取已删除文件的文件名?
问题描述:
我一直在尝试找出如何将图像的文件名放入 SwiftUI 视图中.
I have been trying to find out how to get the filename of an image dropped into a SwiftUI View.
代码片段如下:
struct MainView: View, DropDelegate {
@ObservedObject var userState : UserState
var body : some View {
Group {
if (self.userState.editing) {
BlackoutView()
} else {
DropView()
}
}
.frame(minWidth: 320, idealWidth: 640, maxWidth: .infinity, minHeight: 240, idealHeight: 480, maxHeight: .infinity, alignment: .center)
.onDrop(of: [(kUTTypeImage as String), "public.pdf"], delegate: self)
}
func dropUpdated(info: DropInfo) -> DropProposal? {
let proposal = DropProposal.init(operation: .copy)
return proposal
}
func performDrop(info: DropInfo) -> Bool {
print("perform drop")
userState.editing = true
return true
}
}
当我将图像拖放到应用程序上时,它会运行 performDrop
.如何获取拖放到应用上的图片的文件名?
When I drop an image onto the app, it runs performDrop
. How can one obtain the filename of the image dropped onto the app?
它在 macOS 上运行.
It runs on macOS.
答
在 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