12

我怎样才能dropInteraction(_ interaction: UIDropInteraction, performDrop session: UIDropSession)接受除图像以外的其他类型的文件?例如,我从文件应用程序中拖动 PDF 或 MP3。如何接受此文件并获取数据?

我以为我可以使用 NSURL.self,但这似乎只适用于从 Safari 或 textview 拖动的 URL。

4

2 回答 2

13

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
            }
        }
    }
}
于 2017-08-31T13:02:19.193 回答
2

dropInteraction您调用session.loadObjects(ofClass:),您可能已经拥有并且尝试过UIImageand NSURL

ofClass需要符合NSItemProviderReading文档)。符合它的默认类是NSStringNSAttributedStringNSURLUIColorUIImage。对于其他任何事情,我认为您需要制作一个符合协议的自定义类,public.mp3用作UTI。您的自定义类将有一个init(itemProviderData: Data, typeIdentifier: String)初始化程序,它应该为您提供一袋字节 ( itemProviderData),即 MP3 数据。从那里,您应该能够根据需要写出您的文件。

于 2017-06-16T20:27:48.370 回答