iOS 11拖放自定义文件?

问题描述:

有没有人在iOS 11中拖放自定义文件?有大量的标准图像和文本示例,但自定义文件呢?即使像PDF这样的标准文件也很有用。

Has anyone gotten custom files to drag and drop in iOS 11? There are tons of examples of the standard images and text, but what about custom files? Even standard files like PDF would be useful.


  • 方法1:

  • 制作 PDFDocument 类并实现 NSObject,NSItemProviderReading 协议,然后我们只需将 UIImage 更改为 PDFDocument 类,这些实例

    make a PDFDocument class and implements the NSObject, NSItemProviderReading protocol, then we just change the UIImage to PDFDocument class in those tons of examples

    此处提供更多详细信息 - > https://stackoverflow.com/a/45982118/3608824

    more detail here -> https://stackoverflow.com/a/45982118/3608824


    • 方法2:

    另一种方法是因为我们有 kUTTypePDF 统一类型标识符,只要你导入MobileCoreServices ,根据 dropInteraction(_:performDrop :) 文档,我们可以使用这个function loadFileRepresentation(forTypeIdentifi呃:completionHandler:),这样的事情应该有效:

    Another way is since we have this kUTTypePDF Uniform Type Identifier , as long as you import MobileCoreServices, according to dropInteraction(_:performDrop:) document, we can use this function loadFileRepresentation(forTypeIdentifier:completionHandler:), something like this should work:

func dropInteraction(_ interaction: UIDropInteraction, canHandle session: UIDropSession) -> Bool {
    return session.hasItemsConforming(toTypeIdentifiers: [kUTTypePDF as String]) && session.items.count == 1
}

func dropInteraction(_ interaction: UIDropInteraction, sessionDidUpdate session: UIDropSession) -> UIDropProposal {
    return UIDropProposal(operation: .copy)
}

func dropInteraction(_ interaction: UIDropInteraction, performDrop session: UIDropSession) {
    if let itemProvider = (session.items.first)?.itemProvider {
        itemProvider.loadDataRepresentation(forTypeIdentifier: kUTTypePDF as String) { (data, error) in
            // do the work
        }
    }

}