如何在SwiftUI中获取拖放文件的文件名?

9

我一直在尝试找出如何获取拖放到SwiftUI视图中的图像文件名。

以下是代码片段:

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。如何获取拖放到应用程序中的图像的文件名?
此应用程序在macOS上运行。
1个回答

18

在与API(几乎没有文档)奋斗了一个多小时后,以下是我成功的做法:

// 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。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接