美文网首页
iOS App间文件共享

iOS App间文件共享

作者: Eugene_iOS | 来源:发表于2019-04-19 12:28 被阅读0次
    FileSharing.png
    App间文件共享 这里面包含两种需求:
    1、注册App为可共享应用程序,接收应用程序发送方发来的文件路径
    
    2、App本身成为共享文件的发送方,分享文件到其他应用程序(如:微信、QQ、备忘录等等)
    
    实现以上两个需求我们可以使用UIDocumentInteractionController(文件交互控制器)来实现
    

    需求一注册App为可共享应用程序

    1、 在info.plist中注册本App为可共享应用程序以及注册可接受文件类型(pdf、xls、word、image等等)

    若要App能够接收并打开某种文件,App必须向系统注册。 也就是告诉系统我是可共享应用程序、我可以处理这些文件。完成注册需要在Info.plist中添加Document types键,系统将该键中包含的内容进行登记,这样其他程序就可以通过UIDocumentInteractionController文档交互控制器访问到这些信息【DocumentTypes】。

    Info.plist文件.png
    Info-Document Types.png

    2、 AppDelegate中application:openURL:options:方法里,接收处理应用程序发送方发来的文件

    - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url options:(nonnull NSDictionary<NSString *,id> *)options 
    

    需求二 App分享文件到其他应用程序

    • 文件分享创建UIDocumentInteractionController对象,弹出显示菜单,分享文件到目标应用程序
    // 分享的文件必须存储在本地,若为网络文件必须先下载(`path `文件本地路径)
    NSURL *filePath = [NSURL fileURLWithPath:path];
    // 创建UIDocumentInteractionController对象
    self.documentController = [UIDocumentInteractionController interactionControllerWithURL: filePath];
    // 弹出显示菜单,显示能接收该类型文件的应用,由用户选择分享目标应用
    BOOL isOpen = [documentController presentOpenInMenuFromRect:CGRectZero inView:self.view animated:YES];
    if (isOpen) {
        // to do something
    } else {
        // to do something
    }
    
    • 文件预览+分享使用UIDocumentInteractionController可以同时实现文件预览以及在预览控制器中分享文件到其他应用
    // 预览与分享的文件必须存储在本地,若为网络文件必须先下载(`path `文件本地路径)
    NSURL *filePath = [NSURL fileURLWithPath:path];
    // UIDocumentInteractionController对象最好设置全局,避免在调起目标应用之前对象提前释放应用崩溃
    UIDocumentInteractionController  *documentController = [UIDocumentInteractionController interactionControllerWithURL: filePath];
    // 弹出一个全屏的文档预览窗口(在预览窗口中有可分享文件)
    BOOL isOpen = [documentController presentPreviewAnimated:YES];
    if (isOpen) {
        // to do something
    } else {
        // to do something
    }
    

    关于文档预览

    1、用UIDocumentInteractionController实现文档预览
    优点:简单方便
    缺点:仅支持本地预览、UI不可定制
    2、用WKWebViewUIWebView预览
    优点:UI可定制、支持本地+在线预览(UIWebView iOS12后将不在支持,官方推荐WKWebView)
    缺点:xx
    3、用QLPreviewController预览(功能大致与UIDocumentInteractionController相同,但具体还是有区别的)
    若使用可参考官方文档
    4、用CGContexDrawPDFPage实现预览
    优点:可定制化程度高
    缺点:做精细有点困难

    最后附上需求一、二 Demo:
    WKWebView文件预览+分享+应用成为可共享应用程序


    感谢🙏
    UIDocumentInteractionController之程序间文档共享

    官方接口:
    Document Interaction Programming Topics for iOS

    UIDocumentInteractionController:可实现预览以及分享

    Uniform Type Identifiers:设置可共享App的可接收文件类型

    相关文章

      网友评论

          本文标题:iOS App间文件共享

          本文链接:https://www.haomeiwen.com/subject/chhzwqtx.html