做一个IOS聊天APP如何实现发送/预览文件的功能

缺少发送文件功能的聊天界面

导语

环信官方IOS版Demo功能很强大,却没有实现【发送文件】的功能。但是我们在实际项目开发中,用户之间经常需要在聊天窗口发送文件。所以,本文主要介绍在IOS版APP中,如何结合iCloud Drive一步步实现【发送文件】和【预览文件】的功能。

发送iCloud文件

一、认识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功能。

Paste_Image.png

2.授权APP使用iCloud服务:选中【Capabilities】标签,点击开关启用【iCloud】服务,勾选【Services】组中的【iCloud Documents】项,下面的容器【Containers】项会自动选上,如下图所示:

授权iCloud服务

授权与容器

容器是存放在服务器的保存所有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.显示【发送文件】按钮:在聊天窗口的扩展面板中增加【发送文件】的按钮。
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).编译运行项目,进入单聊页面,打开页面底下的扩展面板,就可以看到【发送文件】的按钮已经可以显示出来了。

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://www.imgeek.org/article/825308714

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值