1.自己的APP調用第三方打開文件
主要是使用 UIDocumentInteractionController 類 並實現 UIDocumentInteractionControllerDelegate 的代理方法
@interface HNDownFileViewController ()<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套件,就能調用這些應用打開。
2.第三方APP調用自己的APP,打開文件
在info.plist中添加如下代碼
1 <array> 2 <dict> 3 <key>CFBundleTypeName</key> 4 <string>com.myapp.common-data</string> 5 <key>LSItemContentTypes</key> 6 <array> 7 <string>com.microsoft.powerpoint.ppt</string> 8 <string>public.item</string> 9 <string>com.microsoft.word.doc</string> 10 <string>com.adobe.pdf</string> 11 <string>com.microsoft.excel.xls</string> 12 <string>public.image</string> 13 <string>public.content</string> 14 <string>public.composite-content</string> 15 <string>public.archive</string> 16 <string>public.audio</string> 17 <string>public.movie</string> 18 <string>public.text</string> 19 <string>public.data</string> 20 </array> 21 </dict> 22 </array>
這在系統中添加了參數,如果有以上類型的文件,第三方應用可以調用我們的APP進行操作。
在第三方調用我們的APP后,會調用如下方法
1 - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(nullable NSString *)sourceApplication annotation:(id)annotation 2 { 3 if (self.window) { 4 if (url) { 5 NSString *fileNameStr = [url lastPathComponent]; 6 NSString *Doc = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/localFile"] stringByAppendingPathComponent:fileNameStr]; 7 NSData *data = [NSData dataWithContentsOfURL:url]; 8 [data writeToFile:Doc atomically:YES]; 9 [XCHUDTool showOKHud:@"文件已存到本地文件夾內" delay:2.0f]; 10 } 11 } 12 return YES; 13 }
url 就是第三方應用調用時文件的沙盒地址,
@"Documents/localFile" 表示本地文件夾目錄
sourceApplication 是調用我們APP的第三方應用是誰
我們把url傳到我們需要用的界面
可以使用路徑查看保存到本地的文件