IOS 11 dropInteraction performDrop for files

How can I use dropInteraction(_ interaction: UIDropInteraction, performDrop session: UIDropSession) to receive files of a different type than images? Tell instnce that I am dragging a PDF or MP3 from a file application. How can I accept this file and get the data?

I thought I could use NSURL.self, but this seems to work only for the URL being dragged from Safari och textview.

+8
ios drag-and-drop ios11
source share
2 answers

An example for a PDF (com.adobe.pdf UTI) that implements NSItemProviderReading might NSItemProviderReading 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) } } 

Then in your deletet you need to process 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 } } } } 
+8
source share

Inside dropInteraction you call session.loadObjects(ofClass:) , which you probably already have, and tried UIImage and NSURL .

ofClass must match NSItemProviderReading ( Documentation ). The corresponding default classes are: NSString , NSAttributedString , NSURL , UIColor and UIImage . For anything else, I think you need to create your own class that conforms to the protocol using public.mp3 as UTI . Your custom class will have an init(itemProviderData: Data, typeIdentifier: String) initializer init(itemProviderData: Data, typeIdentifier: String) , which should provide you with a bag of bytes ( itemProviderData ), which is MP3 data. From there, you can write your file as needed.

0
source share

All Articles