【问题标题】:iOS 11 dropInteraction performDrop for filesiOS 11 dropInteraction performDrop 文件
【发布时间】:2017-11-13 15:50:50
【问题描述】:

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

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

【问题讨论】:

    标签: ios drag-and-drop ios11


    【解决方案1】:

    实现NSItemProviderReading 的 PDF (com.adobe.pdf UTI) 示例可能是这样的:

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

    【讨论】:

    • 谢谢,试过了,但总是崩溃...你设法让它工作了吗?
    • 嗯,您是否尝试过从“文件”应用中拖动?我不断收到 libc++abi.dylib:以 NSException 类型的未捕获异常终止。 P.S - 如果我从在线示例 PDF 中拖动它可以工作。只是不是来自“文件”应用?
    • dropInteraction(_ interaction: UIDropInteraction, sessionDidUpdate session: UIDropSession) 里有什么??
    • 如何获得选定的文件名和位置?
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2021-12-23
      • 2021-12-06
      • 1970-01-01
      • 2019-07-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-22
      • 2018-03-04
      相关资源
      最近更新 更多