【问题标题】:Drag and drop, catalyst拖放,催化剂
【发布时间】:2020-06-11 09:47:16
【问题描述】:

我正在尝试使用拖放方法将 .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)
    }
}

【问题讨论】:

    标签: swift macos drag-and-drop mac-catalyst drop


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-08
      • 2020-01-05
      • 2020-12-14
      • 2013-04-10
      • 1970-01-01
      • 1970-01-01
      • 2023-04-02
      • 2020-08-03
      相关资源
      最近更新 更多