iOS -- 在app中打開第三方應用

一: 在app中使用第三放應用(wps 等)打開本地文檔。app

 1. 獲得本地文檔的路徑

    NSURL *url = [NSURL fileURLWithPath:localPath];url

2.建立文檔對象

   _documentInteractionController = [UIDocumentInteractionControllerspa

                                          interactionControllerWithURL:url];代理

3.設置代理 (UIDocumentInteractionControllerDelegate)

     [_documentInteractionController setDelegate:self]; excel

4. 實現代理方法     

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

    return self;blog

    }    文檔

5. 跳轉/預覽

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

 5.2 預覽    [_documentInteractionController presentPreviewAnimated:YES];it

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

相關文章
相關標籤/搜索