ios调用第三方程序打开文件,以及第三方调用自己的APP打开文件

一.自己的APP调用第三方打开文件

主要是使用 UIDocumentInteractionController 类 并实现 UIDocumentInteractionControllerDelegate的代理方法

@interface ViewController ()<UIDocumentInteractionControllerDelegate>

@property (nonatomic, strong) UIDocumentInteractionController *documentInteractionController;

@end

- (void)viewDidLoad {
    [super viewDidLoad];
    //url 为需要调用第三方打开的文件地址
    NSURL *url = [NSURL fileURLWithPath:_dict[@"path"]];
        _documentInteractionController = [UIDocumentInteractionController
                                              interactionControllerWithURL:url];
        [_documentInteractionController setDelegate:self];

        [_documentInteractionController presentOpenInMenuFromRect:CGRectZero inView:self.view animated:YES];
}

需要在真机上调试,例子中打开的是 doc文件,如果手机上装了WPS或者office套件,就能调用这些应用打开。
当然,如果你在模拟器上也安装了一个马上要介绍的“第三方调用自己的APP打开文件”的应用,也可以在模拟器上试试。

二.第三方APP调用自己的APP,打开文件

1.在info.plist中添加如下代码

<key>CFBundleDocumentTypes</key>
    <array>
        <dict>
            <key>CFBundleTypeName</key>
            <string>com.myapp.common-data</string>
            <key>LSItemContentTypes</key>
            <array>
                <string>com.microsoft.powerpoint.ppt</string>
                <string>public.item</string>
                <string>com.microsoft.word.doc</string>
                <string>com.adobe.pdf</string>
                <string>com.microsoft.excel.xls</string>
                <string>public.image</string>
                <string>public.content</string>
                <string>public.composite-content</string>
                <string>public.archive</string>
                <string>public.audio</string>
                <string>public.movie</string>
                <string>public.text</string>
                <string>public.data</string>
            </array>
        </dict>
    </array>

这在系统中添加了参数,如果有以上类型的文件,第三方应用可以调用我们的APP进行操作。

2.在第三方调用我们的APP后,会调用如下方法

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(nullable NSString *)sourceApplication annotation:(id)annotation
{
     if (self.window) {
         if (url) {
             NSString *fileNameStr = [url lastPathComponent];
             NSString *Doc = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/localFile"] stringByAppendingPathComponent:fileNameStr];
             NSData *data = [NSData dataWithContentsOfURL:url];
             [data writeToFile:Doc atomically:YES];
             self.alert.message = @"文件已存到本地文件夹内";
             [self.alert show];
         }
     }
     return YES;
}

注:
url 就是第三方应用调用时文件的沙盒地址,
@"Documents/localFile" 表示本地文件夹目录
sourceApplication 是调用我们APP的第三方应用是谁
我们把url传到我们需要用的界面
可以使用路径查看保存到本地的文件

猜你喜欢

转载自blog.csdn.net/qcx321/article/details/76999763