iOS 11 dropInteraction performDrop 文件 [英] iOS 11 dropInteraction performDrop for files
问题描述
如何使用 dropInteraction(_interaction: UIDropInteraction, performDrop session: UIDropSession)
来接受除图片以外的其他类型的文件?例如,我从文件应用程序中拖动 PDF 或 MP3.如何接受此文件并获取数据?
How can I use dropInteraction(_ interaction: UIDropInteraction, performDrop session: UIDropSession)
to accept other type of files than images? Say for instnce that I drag a PDF or MP3 from the files app. How can I accept this file and get the data?
我以为我可以使用 NSURL.self,但这似乎只适用于从 Safari 或 textview 拖动的 URL.
I thought I could use NSURL.self, but that only seems to work for URL's dragged from Safari och a textview.
推荐答案
实现 NSItemProviderReading
的 PDF (com.adobe.pdf UTI) 示例可能是这样的:
An example for PDF (com.adobe.pdf UTI) implementing NSItemProviderReading
could be something like this:
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:
Then in your delegate you need to handle this 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
}
}
}
}
这篇关于iOS 11 dropInteraction performDrop 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!