iOS 11 dropInteraction performDrop for files

和自甴很熟 提交于 2019-12-29 06:45:08

问题


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?

I thought I could use NSURL.self, but that only seems to work for URL's dragged from Safari och a textview.


回答1:


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)
    }
}

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
            }
        }
    }
}



回答2:


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

ofClass needs to conform to NSItemProviderReading (Documentation). The default classes that conform to it are NSString, NSAttributedString, NSURL, UIColor, and UIImage. For anything else, I think you will need to make a custom class conforming to the protocol, using public.mp3 as the UTI. Your custom class will have a init(itemProviderData: Data, typeIdentifier: String) initializer that should give you a bag of bytes (itemProviderData) that is the MP3s data. From there, you should be able to write out your file as needed.



来源:https://stackoverflow.com/questions/44494871/ios-11-dropinteraction-performdrop-for-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!