字數(shù)1793 閱讀9834 評論32 喜歡119
好友和聊天流程圖
在看這篇文章之前站粟,你需要配置好服務(wù)器,以及完成注冊和登錄的基本功能,才能繼續(xù)好友和聊天的操作撮竿。
下面兩篇文章是環(huán)境配置和注冊宠默、登錄功能的詳細介紹:
另外必須了解一些CoreData相關(guān)知識
好友
點擊登錄之后贴膘,驗證成功就會跳到好友頁面。這個時候需要顯示你已經(jīng)有的好友抬虽。
那么在tableViewCell中顯示好友姓名官觅,需要數(shù)據(jù)源,數(shù)據(jù)源從服務(wù)器獲看你是否有好友阐污,檢索到你的好友后把他顯示在列表上休涤。
xmpp中管理好友的類是XMPPRoster,并且使用coredata來儲存好友,達到數(shù)據(jù)持久化的效果笛辟。
那么我們可以將獲取儲存好友的倉庫和xmppRoster對象的初始化封裝在XMPPManager中功氨。
在.h文件中聲明:
//好友管理
@property(nonatomic,strong)XMPPRosterxmppRoster;
遵循代理:
@interface XMPPManager : NSObject
在 .m文件中重寫init方法中:
//2.好友管理//獲得一個存儲好友的CoreData倉庫,用來數(shù)據(jù)持久化? ? XMPPRosterCoreDataStorage rosterCoreDataStorage = [XMPPRosterCoreDataStorage sharedInstance];//初始化xmppRoster? ? self.xmppRoster = [[XMPPRoster alloc]initWithRosterStorage:rosterCoreDataStorage dispatchQueue:dispatch_get_main_queue()];//激活? [self.xmppRoster activate:self.xmppStream];//設(shè)置代理? [self.xmppRoster addDelegate:self delegateQueue:dispatch_get_main_queue()];
接收好友請求隘膘。
將接收到好友請求的方法也封裝在XMPPManager中:
// 收到好友請求執(zhí)行的方法-(void)xmppRoster:(XMPPRoster )sender didReceivePresenceSubscriptionRequest:(XMPPPresence )presence{ self.fromJid = presence.from; UIAlertView alert = [[UIAlertView alloc]initWithTitle:@"提示:有人添加你" message:presence.from.user? delegate:self cancelButtonTitle:@"拒絕" otherButtonTitles:@"OK", nil]; [alert show];}
-(void)alertView:(UIAlertView )alertView clickedButtonAtIndex:(NSInteger)buttonIndex{? switch (buttonIndex) {? case 0:? [self.xmppRoster rejectPresenceSubscriptionRequestFrom:self.fromJid];? break;? case 1:? [self.xmppRoster acceptPresenceSubscriptionRequestFrom:self.fromJid andAddToRoster:YES];? break;? default:? break; }}
添加好友疑故,添加的好友必須是服務(wù)器上存在的用戶,需要看對方是否同意弯菊。對方同意之后纵势,刷新好友列表,顯示出來管钳,同時在服務(wù)器上也要添加钦铁,這里服務(wù)器上用的是coredata來存儲個人的好友信息。
好友頁面實現(xiàn)文件才漆,遵循代理牛曹,數(shù)據(jù)源數(shù)組
在viewDidLoad中完成初始化數(shù)組,設(shè)置代理和添加好友按鈕
這里簡化了添加好友醇滥,寫死了只能添加“張三”黎比,如果需要添加更多超营,可以寫成借口
接下來是tableview數(shù)據(jù)源代理方法
tableview
這時候數(shù)組明顯是沒有jid對象的。獲取jid對象是在XMPPPRoster代理方法中實現(xiàn)的:
pragma mark xmppRoster 的代理方法
pragma mark 開始檢索好友列表的方法-(void)xmppRosterDidBeginPopulating:(XMPPRoster *)sender{? ? NSLog(@"開始檢索好友列表");}
pragma mark 正在檢索好友列表的方法-(void)xmppRoster:(XMPPRoster )sender didRecieveRosterItem:(DDXMLElement )item{? ? NSLog(@"每一個好友都會走一次這個方法");//獲得item的屬性里的jid字符串阅虫,再通過它獲得jid對象? ? NSString jidStr = [[item attributeForName:@"jid"] stringValue];? ? XMPPJID jid = [XMPPJID jidWithString:jidStr];//是否已經(jīng)添加? ? if ([self.rosterJids containsObject:jid]) {? ? ? ? return;? ? }//將好友添加到數(shù)組中去? ? [self.rosterJids addObject:jid];//添加完數(shù)據(jù)要更新UI(表視圖更新)? ? NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.rosterJids.count-1 inSection:0];? ? [self.tableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];}
pragma mark 好友列表檢索完畢的方法-(void)xmppRosterDidEndPopulating:(XMPPRoster )sender{? ? NSLog(@"好友列表檢索完畢");}
4. 刪除好友演闭。列表刪除,數(shù)組刪除颓帝,服務(wù)器刪除米碰。
pragma mark 刪除好友執(zhí)行的方法-(void)tableView:(UITableView )tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath )indexPath{? ? if (editingStyle==UITableViewCellEditingStyleDelete) { //找到要刪除的人? ? ? ? XMPPJID jid = self.rosterJids[indexPath.row];//從數(shù)組中刪除? ? ? ? [self.rosterJids removeObjectAtIndex:indexPath.row];//從Ui單元格刪除? ? ? ? [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic? ? ? ? ];//從服務(wù)器刪除? ? ? ? [[XMPPManager defaultManager].xmppRoster removeUser:jid];? ? }}
5.進入聊天頁面
點擊進入聊天頁面的方法
聊天頁面接受jid值的屬性
聊天
1.發(fā)送普通文本消息
同樣在XMPPManager中進行封裝;
//聊天信息歸檔
@property(nonatomic,strong)XMPPMessageArchivingxmppMessageArchiving;
//信息歸檔的上下文
@property(nonatomic,strong)NSManagedObjectContextmessageArchivingContext;
在init初始化時:
//3.保存聊天記錄? //初始化一個倉庫? ? ? ? XMPPMessageArchivingCoreDataStorage *messageStorage = [XMPPMessageArchivingCoreDataStorage sharedInstance];? //創(chuàng)建一個消息歸檔對象? ? ? ? self.xmppMessageArchiving = [[XMPPMessageArchiving alloc]initWithMessageArchivingStorage:messageStorage dispatchQueue:dispatch_get_main_queue()];? //激活? ? ? ? [self.xmppMessageArchiving activate:self.xmppStream];? //上下文? ? ? ? self.messageArchivingContext = messageStorage.mainThreadManagedObjectContext;
在聊天頁面的viewDidload中:
發(fā)送普通消息:
-(void)doSend{? ? //創(chuàng)建一個消息對象购城,并且指明接收者? ? XMPPMessage *message = [XMPPMessage messageWithType:@"chat" to:self.chatToJid];? ? //設(shè)置消息內(nèi)容? ? [message addBody:@"呵呵呵呵呵呵呵呵呵呵"];? ? //發(fā)送消息? ? [[XMPPManager defaultManager].xmppStream sendElement:message];? ? //發(fā)送成功或者失敗吕座,有兩種對應(yīng)的代理方法}
消息發(fā)送是否成功,會走下面的代理方法:
xmppStream的代理方法
刷新消息的方法瘪板,需要熟悉CoreData知識
#pragma mark 刷新消息的方法-(void)reloadMessage{? ? ? ? ? ? ? //得到上下文? ? NSManagedObjectContext context = [XMPPManager defaultManager].messageArchivingContext;? ? ? ? ? ? ? //搜索對象? ? NSFetchRequest request = [[NSFetchRequest alloc]init];? ? ? ? ? ? //創(chuàng)建一個實體描述? ? NSEntityDescription entity = [NSEntityDescription entityForName:@"XMPPMessageArchiving_Message_CoreDataObject" inManagedObjectContext:context];? ? [request setEntity:entity];? ? ? ? ? ? //查詢條件? ? NSPredicate pre = [NSPredicate predicateWithFormat:@"streamBareJidStr = %@ AND bareJidStr = %@",[XMPPManager defaultManager].xmppStream.myJID.bare,self.chatToJid.bare];? ? request.predicate = pre;? ? ? ? ? //排序方式? ? NSSortDescriptor sort = [[NSSortDescriptor alloc]initWithKey:@"timestamp" ascending:YES];? ? request.sortDescriptors = @[sort];? ? ? ? ? //執(zhí)行查詢? ? NSError error = nil;? NSArray array = [context executeFetchRequest:request error:&error];? ? if (self.messages.count != 0) {? ? ? ? [self.messages removeAllObjects];? ? }? ? [self.messages addObjectsFromArray:array];? ? [self.tableView reloadData];}
2.顯示聊天記錄
- (NSInteger)tableView:(UITableView )tableView numberOfRowsInSection:(NSInteger)section {
return self.messages.count;
}
- (UITableViewCell )tableView:(UITableView )tableView cellForRowAtIndexPath:(NSIndexPath )indexPath {? ? static NSString cellIndentifier = @"cell";? ? UITableViewCell cell = [tableView dequeueReusableCellWithIdentifier:cellIndentifier];? ? if (cell==nil) {? ? cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellIndentifier];? ? }? //將聊天信息放到cell上? ? //拿到一個聊天消息? ? XMPPMessageArchiving_Message_CoreDataObject message = self.messages[indexPath.row];? ? if (message.isOutgoing == YES) {? ? cell.detailTextLabel.text = message.body;? ? }? ? }else{? ? cell.textLabel.text = message.body;? ? }? ? return cell;}
成功后就可以聊天了:
演示圖
3.發(fā)送圖片等消息(重點)
發(fā)送視頻等其他文件也是一樣吴趴,xmpp中需要將圖片轉(zhuǎn)化成NSData,然后轉(zhuǎn)化成成base64的字符串進行傳輸篷帅,然后接收到之后再反轉(zhuǎn)化成圖片史侣。
首先要訪問系統(tǒng)相冊。
遵循代理:
@interface ChatViewController ()
從系統(tǒng)相冊選擇照片
發(fā)送圖片消息
這時候需要更改cellForRowAtIndexPath:方法魏身,注意紅色部分惊橱。
發(fā)送圖片消息對應(yīng)cell里也需要更改
我把圖片設(shè)置為cell的imageView,所以圖片顯示了在左邊箭昵,說明圖片消息發(fā)送是成功的税朴,視頻等其他類型的消息,也是同樣的原理家制。
圖片消息演示