swift - 拖放,催化剂
问题描述
我正在尝试使用拖放方法将 .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)
}
}
解决方案
好的,我设法让它工作。所以它非常简单,只需要在 performDrop 方法中的文档文件夹中创建一个目录,然后您可以简单地将数据写入文件路径,所以对我来说是:
do {
try url.data!.write(to: filePath, options: .atomic)
print("succes")
} catch {
print("Failed while storing files.")
}
其中 filePath 指的是 .mp3 文件。而已。我想也许我不能以这种方式播放 mp3,但它就像一个魅力。唯一不起作用的是获得与原始数据相同的文件名。但我相信这也有一个技巧:)
推荐阅读
- c++ - Unicode 字符正在打印,但不如预期
- laravel - 错误:创建表单操作字段的未定义路由 - laravel 5.8
- java - 在不使用 ArrayList 的情况下创建具有原始数组重复元素的数组?
- arrays - 尴尬的数组:沿命名轴使用布尔掩码进行花式索引
- swift - UIImageView 没有在 UITableViewCell 中塑造成正确的圆形
- pandas - 如何在 pandas 中使用 pivot_table 索引数据?
- swift - “Thread1:致命错误:在展开可选值时意外发现 nil”
- javascript - 有没有办法禁用 Select 2 的选项,它的值大于 Select 1 中选择的选项的值
- docusignapi - 预填充的锚标签宽度高度问题
- json - 在单个键上合并同一数组中的对象