做一个IOS聊天APP如何实现发送/预览文件的功能
2017-03-20 10:13
911 查看
导语
环信官方IOS版Demo功能很强大,却没有实现【发送文件】的功能。但是我们在实际项目开发中,用户之间经常需要在聊天窗口发送文件。所以,本文主要介绍在IOS版APP中,如何结合iCloud Drive一步步实现【发送文件】和【预览文件】的功能。一、认识iCloud Drive
iCloud官方文档
这里可以看到iCloud的一些官方介绍以及使用方式,刚开始暂时不必要深入了解。iCloud Drive, 各类文件,在你的各种设备呈现
http://www.apple.com/cn/icloud/icloud-drive/
iCloud Drive 常见问题
https://support.apple.com/zh-cn/HT201104
为什么我们要用iCloud Drive
由于受ios系统的限制(越狱的iphone当然不受限制),app并不能直接访问系统中的文件,所以只能通过iCloud Drive选取文件。二、配置项目支持iCloud Drive
我们以环信官方Demo项目为例进行示范操作,V3.3.0版Demo完整源码下载地址:http://www.easemob.com/download/im
1.下载完项目后,用Xcode打开ChatDemo-UI3.0.xcodeproj,然后更改项目的【Bundle Identifier】为【com.easemob.enterprise.demo.ui.dabiaoge】(自己设置一个独一无二的),并且选择相应的开发证书:
为项目设置一个独一无二的【Bundle Identifier】,才能确保在appstore开发者账户下启用iCloud功能。
2.授权APP使用iCloud服务:选中【Capabilities】标签,点击开关启用【iCloud】服务,勾选【Services】组中的【iCloud Documents】项,下面的容器【Containers】项会自动选上,如下图所示:
授权与容器
容器是存放在服务器的保存所有app数据的一个概念性位置,分为公有数据库与私有数据库。
3.在plist文件中增加配置项:用【Source Code】方式打开项目中的【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>
三、实现【发送文件】功能
1.显示【发送文件】按钮:在聊天窗口的扩展面板中增加【发送文件】的按钮。(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).编译运行项目,进入单聊页面,打开页面底下的扩展面板,就可以看到【发送文件】的按钮已经可以显示出来了。
2.点击【发送文件】按钮,使用UIDocumentPickerViewController打开iCloud文档页面:
文件选择控制器(UIDocumentPickerViewController)可以让用户在程序外访问程序的沙盒。是app间共享文件的一种简单方式。它也支持一些复杂方式,比如用户可能在多个app中编辑同一个文件。
文件选择器可以访问多个文件提供者的文件。比如,iClound可以让你访问其他app存储在iClound的文件,第三方开发者也可以提供文件
(注意:在mac或者windows系统上往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];
编译运行,效果如下图所示:
四、实现【预览文件】功能
点击聊天窗口中的文件类型消息,使用UIDocumentInteractionController打开文件预览窗口查看文件内容。文件交互控制器(UIDocumentInteractionController类的实例)为用户提供可接收程序来处理文件,使用起来非常灵活,功能也比较强大。它除了支持同设备上app之间的文档共享外,还可以实现文档的预览、打印、发邮件以及复制。
要使用一个文件交互控制器(UIDocumentInteractionController类的实例),需要以下步骤:
- 为每个你想打开的文件创建一个UIDocumentInteractionController类的实例;
- 实现UIDocumentInteractionControllerDelegate代理;
- 显示预览窗口/显示菜单。
在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 = ^{ //发送已读回执 [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>
点击聊天窗口后,查看文件的效果如下图所示:
这样,一个简单的发送、预览文件功能就完成了。
技巧:如何参考代码实现功能
在百度网盘中下载本项目的完整源码,然后在xcode中打开项目,全局搜索【add by martin】,即可找到作者增加的相关代码。https://pan.baidu.com/s/1c269Znq
如有问题,请加入【环信互帮互助群】(群号:340452063)提问。
相关文章参考
昵称和头像的显示与更新 http://docs.easemob.com/im/490integrationcases/10nicknameandroid中如何显示开发者服务器上的昵称和头像 http://www.imgeek.org/article/825307856
IOS中如何显示开发者服务器上的昵称和头像 http://www.imgeek.org/article/825307855
IOS快速集成环信IM - 基于官方的Demo优化,5分钟集成环信IM功能 http://www.imgeek.org/article/825307886
草草们的忧伤:环信IM昵称和头像 http://www.imgeek.org/article/825308536
IOS中环信聊天窗口如何实现文件发送和预览的功能 http://www.imgeek.org/question/6260
一言不合你就用环信搞个直播APP http://blog.csdn.net/mengmakies/article/details/51794248
原文:http://www.imgeek.org/article/825308714
相关文章推荐
- 一个功能,两个平台,三种语言 -(iOS,Swift,Android)App代码实现对比篇
- 如何在App中实现IM功能之五快速实现图片接收和发送——箭扣科技Arrownock
- 如何在App中实现IM功能之七快速实现聊天列表排序模块——箭扣科技Arrownock
- iOS开发之使用UICollectionView实现美团App的分类功能【偶现大众点评App的一个小bug】
- android学习笔记(5)-一个搜索文件的APP(2)-搜索功能的实现
- iOS开发中如何实现app作为外设被连接的功能?
- 如何实现VB中打开图像文件时的预览功能
- 如何实现VB中打开图像文件时的预览功能
- 【如何快速的开发一个完整的iOS直播app】(点赞功能)
- 最近做了一个类似社交的网站,看到新浪微博右侧有一个网页在线聊天的功能,如何才能实现网页在线聊天功能(新浪微博这种聊天)?
- 如何在App中实现朋友圈功能之四在朋友圈中添加发送图片功能——箭扣科技Arrownock
- 如何在一个工程里面实现不同的功能打入不同的日志文件中【log4net】
- 请问:如何实现文件日志功能?要求每天换一个文件。文件名以日期区分
- 实现一个录音播放功能的app(ios)
- 如何为iOS app添加AirDrop文件分享功能
- 如何在App中实现IM功能之四创建稳健的消息发送模块——箭扣科技Arrownock
- 如何在App中实现IM功能之七快速实现聊天列表排序模块——箭扣科技Arrownock
- 如何在App中实现IM功能之五快速实现图片接收和发送——箭扣科技Arrownock
- objective-c开发iosapp如何实现一个页面通知另一个页面调用某函数?
- 如何在App中实现IM功能之四创建稳健的消息发送模块——箭扣科技Arrownock