做一個IOS聊天APP如何實(shí)現(xiàn)發(fā)送/預(yù)覽文件的功能

缺少發(fā)送文件功能的聊天界面

導(dǎo)語

環(huán)信官方IOS版Demo功能很強(qiáng)大,卻沒有實(shí)現(xiàn)【發(fā)送文件】的功能。但是我們在實(shí)際項(xiàng)目開發(fā)中,用戶之間經(jīng)常需要在聊天窗口發(fā)送文件。所以,本文主要介紹在IOS版APP中,如何結(jié)合iCloud Drive一步步實(shí)現(xiàn)【發(fā)送文件】和【預(yù)覽文件】的功能。

發(fā)送iCloud文件

一、認(rèn)識iCloud Drive

iCloud官方文檔

這里可以看到iCloud的一些官方介紹以及使用方式,剛開始暫時不必要深入了解。
iCloud Drive, 各類文件,在你的各種設(shè)備呈現(xiàn)
http://www.apple.com/cn/icloud/icloud-drive/

iCloud Drive 常見問題
https://support.apple.com/zh-cn/HT201104

為什么我們要用iCloud Drive

由于受ios系統(tǒng)的限制(越獄的iphone當(dāng)然不受限制),app并不能直接訪問系統(tǒng)中的文件,所以只能通過iCloud Drive選取文件。

二、配置項(xiàng)目支持iCloud Drive

我們以環(huán)信官方Demo項(xiàng)目為例進(jìn)行示范操作,V3.3.0版Demo完整源碼下載地址:
http://www.easemob.com/download/im

1.下載完項(xiàng)目后,用Xcode打開ChatDemo-UI3.0.xcodeproj,然后更改項(xiàng)目的【Bundle Identifier】為【com.easemob.enterprise.demo.ui.dabiaoge】(自己設(shè)置一個獨(dú)一無二的),并且選擇相應(yīng)的開發(fā)證書:

為項(xiàng)目設(shè)置一個獨(dú)一無二的【Bundle Identifier】,才能確保在appstore開發(fā)者賬戶下啟用iCloud功能。

Paste_Image.png

2.授權(quán)APP使用iCloud服務(wù):選中【Capabilities】標(biāo)簽,點(diǎn)擊開關(guān)啟用【iCloud】服務(wù),勾選【Services】組中的【iCloud Documents】項(xiàng),下面的容器【Containers】項(xiàng)會自動選上,如下圖所示:

授權(quán)iCloud服務(wù)
授權(quán)與容器

容器是存放在服務(wù)器的保存所有app數(shù)據(jù)的一個概念性位置,分為公有數(shù)據(jù)庫與私有數(shù)據(jù)庫。


3.在plist文件中增加配置項(xiàng):用【Source Code】方式打開項(xiàng)目中的【ChatDemo-UI3.0-Info.plist】文件,在文件末尾新增如下配置:

    <key>com.apple.developer.icloud-container-identifiers</key>
    <array>
        <string>iCloud.$(CFBundleIdentifier)</string>
    </array>
    <key>com.apple.developer.ubiquity-container-identifiers</key>
    <array>
        <string>$(AppIdentifierPrefix)$(CFBundleIdentifier)</string>
    </array>
    <key>com.apple.developer.ubiquity-kvstore-identifier</key>
    <string>$(AppIdentifierPrefix)$(CFBundleIdentifier)</string>

三、實(shí)現(xiàn)【發(fā)送文件】功能

1.顯示【發(fā)送文件】按鈕:在聊天窗口的擴(kuò)展面板中增加【發(fā)送文件】的按鈕。


Paste_Image.png

(1).在EaseChatBarMoreView.h增加如下代碼:

// 第130行
- (void)moreViewFileTransferAction:(EaseChatBarMoreView *)moreView;

(2).在EaseChatBarMoreView.m增加如下代碼,按鈕圖片文件需自備:

按鈕圖片
// 第47行
@property (nonatomic, strong) UIButton *fileTransterButton;
// 第137行
_fileTransterButton =[UIButton buttonWithType:UIButtonTypeCustom];
[_fileTransterButton setFrame:CGRectMake(insets * 2 + CHAT_BUTTON_SIZE, 10 * 2 + CHAT_BUTTON_SIZE + 10, CHAT_BUTTON_SIZE , CHAT_BUTTON_SIZE)];
[_fileTransterButton setImage:[UIImage imageNamed:@"chatBar_colorMore_file"] forState:UIControlStateNormal];
[_fileTransterButton setImage:[UIImage imageNamed:@"chatBar_colorMore_fileSelected"] forState:UIControlStateHighlighted];
[_fileTransterButton addTarget:self action:@selector(fileTransferAction) forControlEvents:UIControlEventTouchUpInside];
_fileTransterButton.tag = MOREVIEW_BUTTON_TAG + 5;
_maxIndex = 5;
[_scrollview addSubview:_fileTransterButton];
// 第346行
- (void)fileTransferAction
{
    if (_delegate && [_delegate respondsToSelector:@selector(moreViewFileTransferAction:)]) {
        [_delegate moreViewFileTransferAction:self];
    }
}

(3).編譯運(yùn)行項(xiàng)目,進(jìn)入單聊頁面,打開頁面底下的擴(kuò)展面板,就可以看到【發(fā)送文件】的按鈕已經(jīng)可以顯示出來了。

2.點(diǎn)擊【發(fā)送文件】按鈕,使用UIDocumentPickerViewController打開iCloud文檔頁面:

文件選擇控制器(UIDocumentPickerViewController)可以讓用戶在程序外訪問程序的沙盒。是app間共享文件的一種簡單方式。它也支持一些復(fù)雜方式,比如用戶可能在多個app中編輯同一個文件。

文件選擇器可以訪問多個文件提供者的文件。比如,iClound可以讓你訪問其他app存儲在iClound的文件,第三方開發(fā)者也可以提供文件

注意:在mac或者windows系統(tǒng)上往icloud drive傳文件時,有時候iphone上不能馬上顯示最新的文件列表,這時候只要在iphone上注銷icloud賬號重新登錄即可)

(1).在EaseMessageViewController.m頁面增加如下代碼:

// 第1435行
-(void)moreViewFileTransferAction:(EaseChatBarMoreView *)moreView{
    
    // 隱藏鍵盤
    [self.chatToolbar endEditing:YES];
    
    // ios8+才支持icloud drive功能
    if ([[[UIDevice currentDevice] systemVersion] floatValue] < 8.0) {
        //older than iOS 8 code here
        NSLog(@"IOS8以上才支持icloud drive.");
    } else {
        //iOS 8 specific code here
        NSArray *documentTypes = @[@"public.content", @"public.text", @"public.source-code ", @"public.image", @"public.audiovisual-content", @"com.adobe.pdf", @"com.apple.keynote.key", @"com.microsoft.word.doc", @"com.microsoft.excel.xls", @"com.microsoft.powerpoint.ppt"];
        
        UIDocumentPickerViewController *documentPicker = [[UIDocumentPickerViewController alloc] initWithDocumentTypes:documentTypes inMode:UIDocumentPickerModeOpen];
        documentPicker.delegate = self;
        documentPicker.modalPresentationStyle = UIModalPresentationFormSheet;
        [self presentViewController:documentPicker animated:YES completion:nil];
    }
}

// 選中icloud里的pdf文件
- (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentAtURL:(NSURL *)url {
    BOOL fileUrlAuthozied = [url startAccessingSecurityScopedResource];
    if(fileUrlAuthozied){
        NSFileCoordinator *fileCoordinator = [[NSFileCoordinator alloc] init];
        NSError *error;
        
        [fileCoordinator coordinateReadingItemAtURL:url options:0 error:&error byAccessor:^(NSURL *newURL) {
            
            [self dismissViewControllerAnimated:YES completion:NULL];
            [self sendFileMessageWithURL:newURL displayName:[[url path] lastPathComponent]];
        }];
        [url stopAccessingSecurityScopedResource];
    }else{
        //Error handling
        
    }
}
// 第2083行
- (void)sendFileMessageWithURL:(NSURL *)url displayName:(NSString*)displayName
{
    id progress = nil;
    if (_dataSource && [_dataSource respondsToSelector:@selector(messageViewController:progressDelegateForMessageBodyType:)]) {
        progress = [_dataSource messageViewController:self progressDelegateForMessageBodyType:EMMessageBodyTypeFile];
    }
    else{
        progress = self;
    }
    
    EMMessage *message = [EaseSDKHelper sendFileMessageWithURL:url
                                                   displayName:displayName
                                                            to:self.conversation.conversationId
                                                   messageType:[self _messageTypeFromConversationType]
                                                    messageExt:nil];
    
    [self _sendMessage:message];
}

在EaseSDKHelper.m文件中添加如下代碼:

// 第263行
+ (EMMessage *)sendFileMessageWithURL:(NSURL *)url
                          displayName:(NSString*)displayName
                                   to:(NSString *)to
                          messageType:(EMChatType)messageType
                           messageExt:(NSDictionary *)messageExt
{
    NSData *data = [NSData dataWithContentsOfURL:url];
    EMFileMessageBody *body = [[EMFileMessageBody alloc] initWithData:data displayName:displayName];
    NSString *from = [[EMClient sharedClient] currentUsername];
    EMMessage *message = [[EMMessage alloc] initWithConversationID:to from:from to:to body:body ext:messageExt];
    message.chatType = messageType;
    
    return message;
}

在EaseSDKHelper.h添加如下代碼:

// 第187行
+ (EMMessage *)sendFileMessageWithURL:(NSURL *)url
                          displayName:(NSString*)displayName
                                   to:(NSString *)to
                          messageType:(EMChatType)messageType
                           messageExt:(NSDictionary *)messageExt;

在EaseBubbleView+File.m文件中添加如下代碼:

// 第80行
UIImageView *img = [UIImageView new];
img.frame = CGRectMake(EaseMessageCellPadding, EaseMessageCellPadding, 30, 30);
img.image = [UIImage imageNamed:@"chatBar_colorMore_file"];
[self.backgroundImageView addSubview:img];

編譯運(yùn)行,效果如下圖所示:

四、實(shí)現(xiàn)【預(yù)覽文件】功能

點(diǎn)擊聊天窗口中的文件類型消息,使用UIDocumentInteractionController打開文件預(yù)覽窗口查看文件內(nèi)容。

文件交互控制器(UIDocumentInteractionController類的實(shí)例)為用戶提供可接收程序來處理文件,使用起來非常靈活,功能也比較強(qiáng)大。它除了支持同設(shè)備上app之間的文檔共享外,還可以實(shí)現(xiàn)文檔的預(yù)覽、打印、發(fā)郵件以及復(fù)制。


要使用一個文件交互控制器(UIDocumentInteractionController類的實(shí)例),需要以下步驟:

  • 為每個你想打開的文件創(chuàng)建一個UIDocumentInteractionController類的實(shí)例;
  • 實(shí)現(xiàn)UIDocumentInteractionControllerDelegate代理;
  • 顯示預(yù)覽窗口/顯示菜單。

在EaseMessageViewController.m頁面增加如下代碼:

// 第52行
UIDocumentInteractionController *_fileInteractionController;
// 第872行
// 打開文件
- (void)_fileMessageCellSelected:(id<IMessageModel>)model
{
    _scrollToBottomWhenAppear = NO;
    EMFileMessageBody *body = (EMFileMessageBody*)model.message.body;
    
    //判斷本地路徑是否存在
    NSString *localPath = [model.fileLocalPath length] > 0 ? model.fileLocalPath : body.localPath;
    if ([localPath length] == 0) {
        [self showHint:NSLocalizedString(@"message.fileFail", @"file for failure!")];
        return;
    }
    
    dispatch_block_t block = ^{
        //發(fā)送已讀回執(zhí)
        [self _sendHasReadResponseForMessages:@[model.message]
                                       isRead:YES];
        
        int index = (int)[localPath rangeOfString:@"/" options:NSBackwardsSearch].location;;
        NSString *dir = [localPath substringToIndex:index];
        NSString *newLocalPath = [NSString stringWithFormat:@"%@/%@", dir, model.fileName];
        
        // 更改文件名
        if (![[NSFileManager defaultManager] fileExistsAtPath:newLocalPath]) {
            NSError *error = nil;
            [[NSFileManager defaultManager] linkItemAtPath:localPath toPath:newLocalPath error:&error];
        }
        
        [self openFileViewController:newLocalPath];
    };
    
    if (body.downloadStatus == EMDownloadStatusSuccessed && [[NSFileManager defaultManager] fileExistsAtPath:localPath])
    {
        block();
        return;
    }
    
    [self showHudInView:self.view hint:@"文件下載中..."];
    __weak EaseMessageViewController *weakSelf = self;
    [[EMClient sharedClient].chatManager downloadMessageAttachment:model.message progress:nil completion:^(EMMessage *message, EMError *error) {
        [weakSelf hideHud];
        if (!error) {
            block();
        }else{
            [weakSelf showHint:NSEaseLocalizedString(@"message.videoFail", @"video for failure!")];
        }
    }];
}

// 打開文件
-(void)openFileViewController:(NSString *) file_url  {
    
    NSURL *file_URL = [NSURL fileURLWithPath:file_url];
    
    if (file_URL != nil) {
        if (_fileInteractionController == nil) {
            _fileInteractionController = [[UIDocumentInteractionController alloc] init];
            
            _fileInteractionController = [UIDocumentInteractionController interactionControllerWithURL:file_URL];
            _fileInteractionController.delegate = self;
            
        }else {
            _fileInteractionController.URL = file_URL;
        }
        
        [_fileInteractionController presentPreviewAnimated:YES];
    }
}

- (UIViewController *)documentInteractionControllerViewControllerForPreview:(UIDocumentInteractionController *)controller {
    return self;
}

- (UIView *)documentInteractionControllerViewForPreview:(UIDocumentInteractionController *)controller {
    return self.view;
}

- (CGRect)documentInteractionControllerRectForPreview:(UIDocumentInteractionController *)controller {
    return self.view.frame;
}
// 第1308行
[self _fileMessageCellSelected:model];
// 第45行改為
@interface EaseMessageViewController ()<EaseMessageCellDelegate,UIDocumentPickerDelegate,UIDocumentInteractionControllerDelegate>

點(diǎn)擊聊天窗口后,查看文件的效果如下圖所示:

這樣,一個簡單的發(fā)送、預(yù)覽文件功能就完成了。

技巧:如何參考代碼實(shí)現(xiàn)功能

在百度網(wǎng)盤中下載本項(xiàng)目的完整源碼,然后在xcode中打開項(xiàng)目,全局搜索【add by martin】,即可找到作者增加的相關(guān)代碼。
https://pan.baidu.com/s/1c269Znq

如有問題,請加入【環(huán)信互幫互助群】(群號:340452063)提問。

相關(guān)文章參考

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

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

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 173,155評論 25 708
  • 發(fā)現(xiàn) 關(guān)注 消息 iOS 第三方庫、插件、知名博客總結(jié) 作者大灰狼的小綿羊哥哥關(guān)注 2017.06.26 09:4...
    肇東周閱讀 12,223評論 4 61
  • 現(xiàn)在的生活,有許多的人在打游戲,可是他們的事業(yè)呢,卻是一塌糊涂,讓人不堪入目。他們在社會的地位也很卑微。 ...
    竹頭小官閱讀 177評論 8 3
  • 41. 吃罷中飯,兩家人在陳家你一言我一語的閑聊,似是和睦,卻又有幾分尷尬。林爸爸借口酒勁需要下樓去躺一會便回家了...
    暴走小紅帽閱讀 217評論 0 0
  • 事實(shí)上今天不是在新公司的第一天,而是真正的參與工作的第一天。今天有太多的思考,讓我有了再次寫日志的沖動,希望自己可...
    TC_25fe閱讀 468評論 0 0