我怎样才能dropInteraction(_ interaction: UIDropInteraction, performDrop session: UIDropSession)
接受除图像以外的其他类型的文件?例如,我从文件应用程序中拖动 PDF 或 MP3。如何接受此文件并获取数据?
我以为我可以使用 NSURL.self,但这似乎只适用于从 Safari 或 textview 拖动的 URL。
我怎样才能dropInteraction(_ interaction: UIDropInteraction, performDrop session: UIDropSession)
接受除图像以外的其他类型的文件?例如,我从文件应用程序中拖动 PDF 或 MP3。如何接受此文件并获取数据?
我以为我可以使用 NSURL.self,但这似乎只适用于从 Safari 或 textview 拖动的 URL。
PDF ( com.adobe.pdf UTI) 实现的示例NSItemProviderReading
可能是这样的:
class PDFDocument: NSObject, NSItemProviderReading {
let data: Data?
required init(pdfData: Data, typeIdentifier: String) {
data = pdfData
}
static var readableTypeIdentifiersForItemProvider: [String] {
return [kUTTypePDF as String]
}
static func object(withItemProviderData data: Data, typeIdentifier: String) throws -> Self {
return self.init(pdfData: data, typeIdentifier: typeIdentifier)
}
}
然后在您的委托中,您需要处理此 PDFDocument:
extension YourClass: UIDropInteractionDelegate {
func dropInteraction(_ interaction: UIDropInteraction, canHandle session: UIDropSession) -> Bool {
return session.canLoadObjects(ofClass: PDFDocument.self))
}
.
.
.
func dropInteraction(_ interaction: UIDropInteraction, performDrop session: UIDropSession) {
session.loadObjects(ofClass: PDFDocument.self) { [unowned self] pdfItems in
if let pdfs = pdfItems as? [PDFDocument], let pdf = pdfs.first {
// Whatever you want to do with the pdf
}
}
}
}
在dropInteraction
您调用session.loadObjects(ofClass:)
,您可能已经拥有并且尝试过UIImage
and NSURL
。
ofClass
需要符合NSItemProviderReading
(文档)。符合它的默认类是NSString
、NSAttributedString
、NSURL
、UIColor
和UIImage
。对于其他任何事情,我认为您需要制作一个符合协议的自定义类,public.mp3
用作UTI。您的自定义类将有一个init(itemProviderData: Data, typeIdentifier: String)
初始化程序,它应该为您提供一袋字节 ( itemProviderData
),即 MP3 数据。从那里,您应该能够根据需要写出您的文件。