文件查看 UIDocumentInteractionController

UIDocumentInteractionController是從iOS 3.2的SDK開始支持的,它是直接繼承的NSObject,而不是我們想象的UIViewController。

基礎操作

在當前“視圖控制器”里面:

NSString *cachePath = [[NSBundle mainBundle] pathForResource:@"民族" ofType:@"xlsx"]; 
NSURL * pathUrl = [NSURL fileURLWithPath:cachePath];//文件路徑
UIDocumentInteractionController *documentController = [UIDocumentInteractionController interactionControllerWithURL:pathUrl];
documentController.delegate = self;

[documentController presentPreviewAnimated:YES];//跳轉到查看頁面



#pragma mark - UIDocumentInteractionControllerDelegate
-(UIViewController *)documentInteractionControllerViewControllerForPreview:(UIDocumentInteractionController *)controller{
    return self;
}
-(UIView *)documentInteractionControllerViewForPreview:(UIDocumentInteractionController *)controller{
    return self.view;
}
-(CGRect)documentInteractionControllerRectForPreview:(UIDocumentInteractionController *)controller{
    return self.view.bounds;
}
//-(void)documentInteractionController:(UIDocumentInteractionController *)controller willBeginSendingToApplication:(NSString *)application {
//    NSLog(@"%@",controller);
//}
//-(void)documentInteractionController:(UIDocumentInteractionController *)controller didEndSendingToApplication:(NSString *)application {
//    NSLog(@"%@",controller);
//}
//-(void)documentInteractionControllerDidDismissOpenInMenu:(UIDocumentInteractionController *)controller {
//    NSLog(@"%@",controller);
//}




??“支持類型”的展示例子:


播放音樂
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);//文件路徑
NSString *docDir_Str = [paths objectAtIndex:0];
NSString *doc_PathStr = [docDir_Str stringByAppendingString:@"/localFile"];

//直接打開
fullFileNameStr = @"心跳(原味版)-于文文.mp3";
NSString * filePathStr = [doc_PathStr stringByAppendingPathComponent:fullFileNameStr];
NSURL * fileUrl = [NSURL fileURLWithPath:filePathStr];
UIDocumentInteractionController *documentController =  [UIDocumentInteractionController interactionControllerWithURL:fileUrl];
documentController.delegate = self;
//跳轉到文檔查看頁面
[documentController presentPreviewAnimated:YES];

播放音樂,效果:



播放視頻
fullFileNameStr = @"11111.mp4";

播放視頻,效果:



文檔查看
fullFileNameStr = @"民族.xlsx";

文檔查看,效果:


圖片查看
fullFileNameStr = @"chx.jpg";

圖片查看,效果:

其文件查看非常強大,支持很多類型!




??“文檔操作”例子
在自己App里面,對文檔 進行操作:(可自動檢測可進行分享的App)






打開 第三方App里面的文檔

當我們需要打開 在 第三方App里面的文檔時,可以在“info.plist”中添加鍵值對來搞定這個問題:


Source Code格式

<key>CFBundleDocumentTypes</key>
<array>
   <dict>
       <key>CFBundleTypeName</key>          <!--類型名-->
       <string>pdf</string>                 <!--隨意取名字-->
       <key>CFBundleTypeIconFiles</key>     <!--類型文件的icon圖-->
       <array>
           <string>MySmallIcon.png</string>
           <string>MyLargeIcon.png</string>
       </array>
       <key>LSItemContentTypes</key>        <!--所關聯(lián)的UTI格式,一個類型名可以對應多個UTI-->
       <array>
           <string>com.adobe.pdf</string>
       </array>
       <key>LSHandlerRank</key>             <!--是不是app所擁有的類型,Default:不是,Owner:是-->
       <string>Owner</string>
   </dict>
</array>


在以下鏈接中,有文件后綴UTI(統(tǒng)一類型標識符) 的對應表:
https://developer.apple.com/library/mac/#documentation/Miscellaneous/Reference/UTIRef/Articles/System-DeclaredUniformTypeIdentifiers.html


“info.plist”修改實例:(“Property List”格式)


如何導入文檔:

當我們從其他的App,用“readerApp”打開文檔時,會調(diào)用“readerApp”的方法!
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation { }

其中,url對應的就是該文檔位置。
實際在此時,該文檔已經(jīng)復制到“readerApp”的“document/inbox”文件夾下。
我們需要將該文檔移動到其他位置,因為每次其他應用調(diào)用“readerApp”打開該文檔時,都會在inbox文件夾下復制一份文件(不考慮該文件是否已經(jīng)存在),如果多次使用,那么inbox將會占用大量的存儲空間。

總結:記得在移動了文檔后,要刪除掉inbox路徑里面的內(nèi)容!












自己的文檔閱讀APP 書寫??:

1.在“info.plist”里面,添加可以支持的所有類型:(“Source Code格式:)

<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>

這樣,其他應用程序的文檔在使用第三方打開的時候,就可以看到你的應用程序了。

對應的“Property List格式:


文檔查看操作

點擊該文檔,打開
對文檔,進行操作


添加可支持的類型之前 添加可支持的類型之后
無 自己的App,可供選擇
有 自己的App,可供選擇




反復導入文檔:

每次導入,都會在inbox文件夾下復制一份文件。
所以出現(xiàn)了:名稱后面文檔 命名為“-3”的情況




解決操作

導入文檔后,不管是否保存在本地,都要刪除Inbox 面的文件

//fileNameStr:文件名  (導入所產(chǎn)生文檔所在的Url 獲取來的)
NSString * fileNameStr = [_docUrl lastPathComponent];

NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString * docDir_Str = [paths objectAtIndex:0];//沙盒文檔路徑

//刪除文件的路徑
NSString * deleteDocPath = [[docDir_Str stringByAppendingPathComponent:@"Inbox"] stringByAppendingPathComponent:fileNameStr];
//刪除Inbox里面的文件
[[NSFileManager defaultManager] removeItemAtPath:deleteDocPath error:nil]; 




2.文檔導入操作

全局變量:NSURL * _docUrl;//文檔Url

/** 文檔導入 */
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {  
      if (self.window) { 
          if (url) {
              _docUrl = url;
              NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
              NSString *docDir_Str = [paths objectAtIndex:0];
              NSString *pathStr = [docDir_Str stringByAppendingString:@"/localFile"];
              NSFileManager * fileManager = [NSFileManager defaultManager];
              if(![fileManager fileExistsAtPath:pathStr]){
                  //如果不存在,則說明是第一次運行這個程序,那么建立這個文件夾
                  NSString *directryPath = [docDir_Str stringByAppendingPathComponent:@"localFile"];
                  [fileManager createDirectoryAtPath:directryPath withIntermediateDirectories:YES attributes:nil error:nil];
              }
            

              //提醒視圖: UIActionSheet
              UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"是否需要保存文檔?" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"確認" otherButtonTitles:nil];
              [actionSheet showInView:self.window.rootViewController.view];


              //在NSUserDefaults里:保存“從文檔進入App”為YES
              [User_Def setBool:YES forKey:JoinAPPFromDocumVC]; 
              [User_Def synchronize];
            
              //跳轉,查看文檔
              UIDocumentInteractionController *documentController =  [UIDocumentInteractionController interactionControllerWithURL:url];
              documentController.delegate = self;
              [documentController presentPreviewAnimated:YES];//跳轉到查看頁面
          }
     }

}


3.文檔查看UIDocumentInteractionControllerDelegate

#pragma mark - UIDocumentInteractionControllerDelegate
-(UIViewController *)documentInteractionControllerViewControllerForPreview:(UIDocumentInteractionController *)controller{
    return self.window.rootViewController;
}
-(UIView *)documentInteractionControllerViewForPreview:(UIDocumentInteractionController *)controller{
    return self.window.rootViewController.view;
}
-(CGRect)documentInteractionControllerRectForPreview:(UIDocumentInteractionController *)controller{
    return self.window.rootViewController.view.bounds;
}
//-(void)documentInteractionController:(UIDocumentInteractionController *)controller willBeginSendingToApplication:(NSString *)application {
//    NSLog(@"%@",controller);
//}
//-(void)documentInteractionController:(UIDocumentInteractionController *)controller didEndSendingToApplication:(NSString *)application {
//    NSLog(@"%@",controller);
//}
//-(void)documentInteractionControllerDidDismissOpenInMenu:(UIDocumentInteractionController *)controller {
//    NSLog(@"%@",controller);
//}




4.提醒視圖:UIActionSheetDelegate
以及
5.保存操作

#pragma mark - UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    NSLog(@"ACActionSheet delegate - %ld",buttonIndex);

    if (buttonIndex == 0) { //是否考慮 保存
        NSFileManager * fileManager = [NSFileManager defaultManager];
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *docDir_Str = [paths objectAtIndex:0];
        NSString *pathStr = [docDir_Str stringByAppendingString:@"/localFile"];
        NSDirectoryEnumerator *enumerator = [fileManager enumeratorAtPath:pathStr];//遍歷
    
    
        NSArray *fileList = [NSArray arrayWithArray:[fileManager contentsOfDirectoryAtPath:pathStr error:nil]];
        if (fileList.count == 0) { //個數(shù)為0
            NSString * fileNameStr = [_docUrl lastPathComponent];
            NSString * DocPathStr = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/localFile"] stringByAppendingPathComponent:fileNameStr];   //保存的路徑
            NSData * data = [NSData dataWithContentsOfURL:_docUrl];//保存的數(shù)據(jù)
        
            if ([data writeToFile:DocPathStr atomically:YES]) {
                NSString * deleteDocPath = [[docDir_Str stringByAppendingPathComponent:@"Inbox"] stringByAppendingPathComponent:fileNameStr];
                [fileManager removeItemAtPath:deleteDocPath error:nil]; //刪除Inbox里面的文件
            }
        } else {
            for (NSString *fileName in enumerator) {
                NSLog(@"%@",fileName);
                NSString * fileNameStr = [_docUrl lastPathComponent];
                NSString * fileName_total = [fileName componentsSeparatedByString:@" -"][0];
                NSString * fileNameStr_total = [fileNameStr componentsSeparatedByString:@" -"][0];
                if (![fileName_total isEqualToString:fileNameStr_total]) {
                    NSString * DocStr = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/localFile"] stringByAppendingPathComponent:fileNameStr];   //保存的路徑
                    NSData * data = [NSData dataWithContentsOfURL:_docUrl];//保存的數(shù)據(jù)
                
                    if ([data writeToFile:DocStr atomically:YES]) {
                        NSString * deleteDocPath = [[docDir_Str stringByAppendingPathComponent:@"Inbox"] stringByAppendingPathComponent:fileNameStr];
                        [fileManager removeItemAtPath:deleteDocPath error:nil]; //刪除Inbox里面的文件
                    }
                }
            }
        }
    
    } else { //不保存在本地

        //刪除Inbox里面的文件
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *docDir_Str = [paths objectAtIndex:0];
        NSString * fileNameStr = [_docUrl lastPathComponent];
        NSString * deleteDocPath = [[docDir_Str stringByAppendingPathComponent:@"Inbox"] stringByAppendingPathComponent:fileNameStr];
        [[NSFileManager defaultManager] removeItemAtPath:deleteDocPath error:nil];
    }
}




當然,最簡單的 刪除Inbox”里文件操作:

就是 —— 在文檔展示界面消失后,再刪除Inbox面的文件

實現(xiàn)代理方法:

- (void)documentInteractionControllerDidEndPreview:(UIDocumentInteractionController *)controller { //結束 展示文檔
   //(不保存,直接刪除) 刪除“Inbox”里面的文件
   NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
   NSString *docDir_Str = [paths objectAtIndex:0];
   NSString * fileNameStr = [_docUrl lastPathComponent];//文件名
   NSString * deleteDocPath = [[docDir_Str stringByAppendingPathComponent:@"Inbox"] stringByAppendingPathComponent:fileNameStr];
   [[NSFileManager defaultManager] removeItemAtPath:deleteDocPath error:nil];

   NSLog(@"%@",controller);
}















goyohol's essay

最后編輯于
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

  • *面試心聲:其實這些題本人都沒怎么背,但是在上海 兩周半 面了大約10家 收到差不多3個offer,總結起來就是把...
    Dove_iOS閱讀 27,595評論 30 472
  • 218.241.181.202 wxhl60 123456 192.168.10.253 wxhl66 wxhl6...
    CYC666閱讀 1,550評論 0 6
  • Spring Cloud為開發(fā)人員提供了快速構建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,534評論 19 139
  • 今天就本周作業(yè)的讀取txt文件查找了的一些方法,如下: //讀取文本內(nèi)容NSError *error;NSStri...
    霏誠拜咬o閱讀 743評論 0 0
  • 1昨天,秀燕姐在群里轉發(fā)了一篇三節(jié)課的公眾號推送,一篇名為《致一位對生活感到悲觀和絕望的用戶》的推送,讓我們學習一...
    碧落云湮閱讀 282評論 0 0

友情鏈接更多精彩內(nèi)容