拖放技术,催化剂

3
我正在尝试使用拖放方法将Finder中的.mp3文件拖到我的应用程序中(使用Mac Catalyst)。到目前为止,我已成功将(我猜)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)
    }
}
1个回答

3

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

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

其中filePath是指一个.mp3文件的路径。就是这样了。我曾经觉得可能无法用这种方式播放mp3,但它运行得非常好。现在唯一不能正常工作的是获取与原始数据相同的文件名。但我相信也有解决方法 :)


你有解决文件名的问题吗?我正在尝试做类似的事情,但是我就是无法获取有关原始丢弃文件的任何详细信息。 - Marc-André Weibezahn

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