ios UIDocumentInterationController基本使用

IMG_0001.JPG

文章主要寫來日后自己回顧毛秘,不詳細(xì)

1颅和、在項(xiàng)目的info.plist里面添加相應(yīng)的鍵值對,將事先下載好的pdf拖到項(xiàng)目中茎辐,如圖1.0和1.1宪郊,注意不是TARGETS下的info里面添加,在那里面添加會導(dǎo)致程序crash

1.0 下載的pdf拖到項(xiàng)目中
圖1.1 添加所需鍵值對

2拖陆、進(jìn)入程序弛槐,遵循代理<UIDocumentInteractionControllerDelegate>

設(shè)置全局變量或者屬性

    UIDocumentInteractionController *documentIntertactionController;
}

3、創(chuàng)建兩個(gè)button依啰,一個(gè)用來打開其他app乎串,一個(gè)用來預(yù)覽文件,如圖3.1

圖3.1

4速警、打開的方法實(shí)現(xiàn)

// 打開
- (void)openUIDocument{
    NSURL *pathUrl = [[NSBundle mainBundle] URLForResource:@"Steve" withExtension:@".pdf"];   
    documentIntertactionController = [UIDocumentInteractionController interactionControllerWithURL:pathUrl];    
    documentIntertactionController.delegate = self;    
    [self presentOptionsMenu];
}


- (void)presentOptionsMenu{
    [documentIntertactionController presentOptionsMenuFromRect:self.view.bounds inView:self.view animated:YES];
}

以下是上面方法的官方解釋

application to pass to receiver (must be a plist object). default is nil.

// This is the default method you should call to give your users the option to quick look, open, or copy the document.
// Presents a menu allowing the user to Quick Look, open, or copy the item specified by URL.
// This automatically determines the correct application or applications that can open the item at URL.
// Returns NO if the options menu contained no options and was not opened.
// Note that you must implement the delegate method documentInteractionControllerViewControllerForPreview: to get the Quick Look menu item.

5叹誉、點(diǎn)擊打開,如圖5.1闷旧,這是模擬器的效果桂对,在手機(jī)上還有其他軟件,比如微信qq等等

圖5.1

6鸠匀、預(yù)覽對應(yīng)的代碼

// 預(yù)覽
- (void)previewUIDocument{
    NSURL *pathUrl = [[NSBundle mainBundle] URLForResource:@"Steve" withExtension:@".pdf"];
    documentIntertactionController = [UIDocumentInteractionController interactionControllerWithURL:pathUrl];
    documentIntertactionController.delegate = self;
    [self presentUIDocument];
}

- (void)presentUIDocument{
    [documentIntertactionController presentPreviewAnimated:YES];
}
// 預(yù)覽的時(shí)候需要加上系統(tǒng)的代理方法
- (UIViewController *)documentInteractionControllerViewControllerForPreview:(UIDocumentInteractionController *)controller{
    return self;
}

7蕉斜、點(diǎn)擊預(yù)覽,如圖7.1

圖7.1 預(yù)覽

8缀棍、以上為加載本地存在的文件宅此,下面介紹根據(jù)網(wǎng)址打開和預(yù)覽

9、open網(wǎng)上鏈接爬范,代碼如下

- (void)openUIDocument{
    [self openDocument];
}

- (void)openDocument{
    [self pathUrl];  // 該方法在最下面
    
    NSData *data = [NSData dataWithContentsOfURL:_pathUrl];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString  *documentsDirectory = [paths objectAtIndex:0];
    NSString  *filePath = [NSString stringWithFormat:@"%@/%@", documentsDirectory,@"Python核心編程.pdf"];
    BOOL isWriteSuccess = [data writeToFile:filePath atomically:YES];
    
    if(isWriteSuccess) {//success
   
        NSURL *url = [NSURL fileURLWithPath:filePath];
        [self previewPdfWithUrl:url];
        [self presentOptionsMenu];
    }
    else{
        NSLog(@"file not written");
    }
}
- (void)previewPdfWithUrl:(NSURL*)url{
    documentIntertactionController = [UIDocumentInteractionController interactionControllerWithURL:url];
    documentIntertactionController.delegate = self;
}

- (void)presentOptionsMenu{
    [documentIntertactionController presentOptionsMenuFromRect:self.view.bounds inView:self.view animated:YES];
}

效果如圖5.1

10父腕、 預(yù)覽,代碼如下

- (void)previewUIDocument{
    [self previewDocument];
    
}

- (void)previewDocument{

    [self pathUrl];

    NSData *data = [NSData dataWithContentsOfURL:_pathUrl];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString  *documentsDirectory = [paths objectAtIndex:0];
    NSString  *filePath = [NSString stringWithFormat:@"%@/%@", documentsDirectory,@"Python核心編程.pdf"];

    BOOL isWriteSuccess = [data writeToFile:filePath atomically:YES];
    
    if(isWriteSuccess) {//success
        NSLog(@"%@",filePath);
        NSURL *url = [NSURL fileURLWithPath:filePath];
        [self previewPdfWithUrl:url];
        [self presentUIDocument];
    }
    else{
        NSLog(@"file not written");
    }
    
}
- (void)previewPdfWithUrl:(NSURL*)url{
    documentIntertactionController = [UIDocumentInteractionController interactionControllerWithURL:url];
    documentIntertactionController.delegate = self;
}

- (NSURL *)pathUrl{
    if (_pathUrl== nil) {
        NSString *urlString = @"http://platform-test.lejuwanjia.com/api/v1/web/content/sale.order.picture/158/picture/Python核心編程.pdf";
        NSString *urlStr = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
//        _pathUrl = [NSURL URLWithString:urlStr];
        _pathUrl = [NSURL URLWithString:urlStr];
        NSLog(@"pathUrl:%@",_pathUrl);
    }
    return _pathUrl;
}

- (void)presentUIDocument{
    [documentIntertactionController presentPreviewAnimated:YES];
}
- (UIViewController *)documentInteractionControllerViewControllerForPreview:(UIDocumentInteractionController *)controller{
    return self;
}


#pragma mark - url 中文格式化
+ (NSString *)strUTF8Encoding:(NSString *)str
{
    /*! ios9適配的話 打開第一個(gè) */
    if ([[UIDevice currentDevice] systemVersion].floatValue >= 9.0)
    {
         return [str stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLPathAllowedCharacterSet]];
    }
    else
    {
        return [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    }
}

11 網(wǎng)上文件的預(yù)覽需要先緩存到本地青瀑,這時(shí)候可以建一個(gè)緩存目錄璧亮,以便于以后刪除緩存

11.1 如果是請求網(wǎng)絡(luò)然后返回了一個(gè)NSData對象萧诫,這時(shí)候可以先保存到某個(gè)目錄下面,下一個(gè)預(yù)覽的時(shí)候判斷此目錄下是否有文件來減少網(wǎng)絡(luò)請求
- (void)previewWithModel:(OSPAttachFileModel *)model {
// 此model為點(diǎn)擊某行cell時(shí)對應(yīng)的model
        NSString *filePath = [self getFilePathWithModel:model];
        NSFileManager *fileManager = [NSFileManager defaultManager];
        BOOL isDir = NO;
        BOOL existed = [fileManager fileExistsAtPath:filePath isDirectory:&isDir];
        if (existed) {
            NSURL *url = [NSURL fileURLWithPath:filePath];
            [self previewPdfWithUrl:url];
        }else {
            [OSPToast show];
            [[OSPServiceCallsService sharedInstance] queryDocumentWithDocumentId:model.documentId equipmentId:model.equipmentId completion:^(NSData *data,NSHTTPURLResponse * response, NSError * error) {
                [OSPToast dismiss];
                if (data.length) {
                    [self previewDocumentWithFilePath:filePath data:data];
                }
            }];
        }
}

- (NSString *)getFilePathWithModel:(OSPAttachFileModel *)model {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString  *documentsDirectory = [paths objectAtIndex:0];
    
    NSString *dataFilePath = [documentsDirectory stringByAppendingPathComponent:OSPAttchFile];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL isDir = NO;
    BOOL existed = [fileManager fileExistsAtPath:dataFilePath isDirectory:&isDir];
    if (!(isDir && existed)) {
        [fileManager createDirectoryAtPath:dataFilePath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    NSString *documentIdStr = [NSString stringWithFormat:@"%zd", model.documentId];
    NSString *filePath = [NSString stringWithFormat:@"%@/%@-%@", dataFilePath,documentIdStr,model.documentName];
    return filePath;
}

- (void)previewPdfWithUrl:(NSURL*)url {
    _documentInteraction = [UIDocumentInteractionController interactionControllerWithURL:url];
    _documentInteraction.delegate = self;
    [_documentInteraction presentPreviewAnimated:YES];
}

- (void)previewDocumentWithFilePath:(NSString *)filePath data:(NSData *)data {
    BOOL isWriteSuccess = [data writeToFile:filePath atomically:YES];
    if(isWriteSuccess) {//success
        NSURL *url = [NSURL fileURLWithPath:filePath];
        [self previewPdfWithUrl:url];
    }else {
        DLog(@"file not written");
    }
}

11.1preview.png

點(diǎn)擊其中一個(gè)文件枝嘶,先根據(jù)model中的文件名以及id找到對應(yīng)路徑下是否存在文件帘饶,如果存在直接preview,不存在的話根據(jù)model生成的路徑及文件名將下載的NSData write to file 群扶,成功之后preview


對應(yīng)文件路徑及文件名.png
gotofolder.png

根據(jù)model生成的文件及刻,OSPAttachFile為創(chuàng)建的文件夾,易于管理


Snip20190221_9.png

根據(jù)文件filepath竞阐,直接preview


Snip20190221_11.png
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末缴饭,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子骆莹,更是在濱河造成了極大的恐慌颗搂,老刑警劉巖,帶你破解...
    沈念sama閱讀 216,692評論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件幕垦,死亡現(xiàn)場離奇詭異峭火,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)智嚷,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,482評論 3 392
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來纺且,“玉大人盏道,你說我怎么就攤上這事≡芈担” “怎么了猜嘱?”我有些...
    開封第一講書人閱讀 162,995評論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長嫁艇。 經(jīng)常有香客問我朗伶,道長,這世上最難降的妖魔是什么步咪? 我笑而不...
    開封第一講書人閱讀 58,223評論 1 292
  • 正文 為了忘掉前任论皆,我火速辦了婚禮,結(jié)果婚禮上猾漫,老公的妹妹穿的比我還像新娘点晴。我一直安慰自己,他們只是感情好悯周,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,245評論 6 388
  • 文/花漫 我一把揭開白布粒督。 她就那樣靜靜地躺著,像睡著了一般禽翼。 火紅的嫁衣襯著肌膚如雪屠橄。 梳的紋絲不亂的頭發(fā)上族跛,一...
    開封第一講書人閱讀 51,208評論 1 299
  • 那天,我揣著相機(jī)與錄音锐墙,去河邊找鬼礁哄。 笑死,一個(gè)胖子當(dāng)著我的面吹牛贮匕,可吹牛的內(nèi)容都是我干的姐仅。 我是一名探鬼主播,決...
    沈念sama閱讀 40,091評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼刻盐,長吁一口氣:“原來是場噩夢啊……” “哼掏膏!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起敦锌,我...
    開封第一講書人閱讀 38,929評論 0 274
  • 序言:老撾萬榮一對情侶失蹤馒疹,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后乙墙,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體颖变,經(jīng)...
    沈念sama閱讀 45,346評論 1 311
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,570評論 2 333
  • 正文 我和宋清朗相戀三年听想,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了腥刹。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,739評論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡汉买,死狀恐怖衔峰,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情蛙粘,我是刑警寧澤垫卤,帶...
    沈念sama閱讀 35,437評論 5 344
  • 正文 年R本政府宣布,位于F島的核電站出牧,受9級特大地震影響穴肘,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜舔痕,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,037評論 3 326
  • 文/蒙蒙 一评抚、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧伯复,春花似錦盈咳、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,677評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至组底,卻和暖如春丈积,著一層夾襖步出監(jiān)牢的瞬間筐骇,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,833評論 1 269
  • 我被黑心中介騙來泰國打工江滨, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留铛纬,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 47,760評論 2 369
  • 正文 我出身青樓唬滑,卻偏偏與公主長得像告唆,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個(gè)殘疾皇子晶密,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,647評論 2 354

推薦閱讀更多精彩內(nèi)容