我如何使用 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)
}
}
然后在您的委托(delegate)中您需要处理这个 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 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44494871/