iOS -- 在app中打开第三方应用

一: 在app中使用第三放应用(wps 等)打开本地文档。

 1. 得到本地文档的路径

    NSURL *url = [NSURL fileURLWithPath:localPath];

2.创建文档对象

   _documentInteractionController = [UIDocumentInteractionController

                                          interactionControllerWithURL:url];

3.设置代理 (UIDocumentInteractionControllerDelegate)

     [_documentInteractionController setDelegate:self]; 

4. 实现代理方法     

   - (UIViewController *)documentInteractionControllerViewControllerForPreview:(UIDocumentInteractionController *)controller{

    return self;

    }    

5. 跳转/预览

 5.1 跳转:  [_documentInteractionController presentOpenInMenuFromRect:CGRectZero inView:self.view animated:YES];

 5.2 预览    [_documentInteractionController presentPreviewAnimated:YES];

6. plist文件加节点       

<key>CFBundleDocumentTypes</key>

<array>

<dict>

<key>CFBundleTypeName</key>

<string>com.myapp.common-data</string>

<key>LSHandlerRank</key>

<string>Owner</string>

<key>CFBundleTypeRole</key>

<string>Viewer</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>

<string>public.docx</string>

<string>public.doc</string>

</array>

</dict>

</array>

二: 第三方应用回传数据到app

  1.  在appdelete 中添加以下方法        

- (BOOL)application:(UIApplication *)application openURL:(nonnull NSURL *)url options:(nonnull NSDictionary<NSString *,id> *)options {
    if (url != nil) {
        NSString *path = [url absoluteString];
        NSMutableString *string = [[NSMutableString alloc] initWithString:path];
        if ([path hasPrefix:@"file://"]) {
            [string replaceOccurrencesOfString:@"file://" withString:@"" options:NSCaseInsensitiveSearch  range:NSMakeRange(0, path.length)];
        }
        NSLog(@"获取到的文件路径:%@",string);
        
        //使用单例,将获取到的文件路径保存
        ShareModel *share=[ShareModel initShareModel];
        share.trainFilePath=string;   
    }
    return YES;
}

  注意: 只有在第三方中发送或分享至app的文件才能获取到路径 , 在第三方中直接按左上角的返回是不会触发该方法的。

  补充: 在第三方中点击返回在app会调用以下方法           

            applicationWillEnterForeground    /    applicationDidBecomeActive

原文地址:https://www.cnblogs.com/Cyan-zoey/p/6781274.html