首页 > 解决方案 > 拖放,催化剂

问题描述

我正在尝试使用拖放方法将 .mp3 文件从 finder 拖到我的应用程序中(使用 mac 催化剂)。到目前为止,我已经成功地将(我猜)mp3 文件中的原始数据放入一个数组中,但我不确定如何进行。我最终想要的是使用 AVAudioPlayerNodes 播放拖放到应用程序中的 .mp3 文件。这是正确的方法,还是我应该尝试获取文件的 URL,然后将其复制到我的应用程序?任何帮助都是极好的。谢谢你。

代码:委托方法

func dropInteraction(_ interaction: UIDropInteraction, sessionDidUpdate session: UIDropSession) -> UIDropProposal {
      if session.localDragSession == nil {
          print("yes")
          return UIDropProposal(operation: .copy)
      }
        print("no")
      return UIDropProposal(operation: .cancel)
    }

    func dropInteraction(_ interaction: UIDropInteraction, performDrop session: UIDropSession) {
        print("somethng happened")
        session.loadObjects(ofClass: MP3Class.self) { objects in
            for url in objects as! [MP3Class] {
                print(url)
                print(objects)
            }
        }
    }

    func dropInteraction(_ interaction: UIDropInteraction, canHandle session: UIDropSession) -> Bool {
        return session.canLoadObjects(ofClass: MP3Class.self)
    }

    func customEnableDropping(on view: UIView, dropInteractionDelegate: UIDropInteractionDelegate) {
        let dropInteraction = UIDropInteraction(delegate: dropInteractionDelegate)
        view.addInteraction(dropInteraction)
    } 

自定义 mp3 类:

class MP3Class: NSObject, NSItemProviderReading {
    let data: Data?

    required init(mp3Data: Data, typeIdentifier: String) {
        data = mp3Data
    }

    static var readableTypeIdentifiersForItemProvider: [String] {
        return [kUTTypeMP3 as String]
    }

    static func object(withItemProviderData data: Data, typeIdentifier: String) throws -> Self {
        return self.init(mp3Data: data, typeIdentifier: typeIdentifier)
    }
}

标签: swiftmacosdrag-and-dropmac-catalystdrop

解决方案


好的,我设法让它工作。所以它非常简单,只需要在 performDrop 方法中的文档文件夹中创建一个目录,然后您可以简单地将数据写入文件路径,所以对我来说是:

        do {
            try url.data!.write(to: filePath, options: .atomic)
            print("succes")
        } catch {
            print("Failed while storing files.")
        }

其中 filePath 指的是 .mp3 文件。而已。我想也许我不能以这种方式播放 mp3,但它就像一个魅力。唯一不起作用的是获得与原始数据相同的文件名。但我相信这也有一个技巧:)


推荐阅读