如何在 SwiftUI 中获取已删除文件的文件名? [英] How to get the filename of dropped file in SwiftUI?

查看:51
本文介绍了如何在 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

这篇关于如何在 SwiftUI 中获取已删除文件的文件名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆