自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

iOS中XMPP簡單聊天實(shí)現(xiàn) 好友和聊天

移動開發(fā)
在看這篇文章之前,你需要配置好服務(wù)器,以及完成注冊和登錄的基本功能,才能繼續(xù)好友和聊天的操作。

好友和聊天流程圖

在看這篇文章之前,你需要配置好服務(wù)器,以及完成注冊和登錄的基本功能,才能繼續(xù)好友和聊天的操作。

下面兩篇文章是環(huán)境配置和注冊、登錄功能的詳細(xì)介紹:
XMPP的mysql和openfire環(huán)境配置
iOS中XMPP簡單聊天實(shí)現(xiàn) 注冊和登錄

另外必須了解一些CoreData相關(guān)知識

好友

  1. 點(diǎn)擊登錄之后,驗(yàn)證成功就會跳到好友頁面。這個時(shí)候需要顯示你已經(jīng)有的好友。
    那么在tableViewCell中顯示好友姓名,需要數(shù)據(jù)源,數(shù)據(jù)源從服務(wù)器獲看你是否有好友,檢索到你的好友后把他顯示在列表上。
    xmpp中管理好友的類是 XMPPRoster,并且使用coredata來儲存好友,達(dá)到數(shù)據(jù)持久化的效果。
    那么我們可以將獲取儲存好友的倉庫和xmppRoster對象的初始化封裝在XMPPManager中。
    在.h文件中聲明:

    1. //好友管理 
    2. @property(nonatomic,strong)XMPPRoster xmppRoster; 

    遵循代理:

    1. @interface XMPPManager : NSObject<XMPPStreamDelegate,XMPPRosterDelegate> 

    在 .m文件中重寫init方法中:
    1. //2.好友管理//獲得一個存儲好友的CoreData倉庫,用來數(shù)據(jù)持久化 
    2.     XMPPRosterCoreDataStorage rosterCoreDataStorage = [XMPPRosterCoreDataStorage sharedInstance]; 
    3. //初始化xmppRoster 
    4.     self.xmppRoster = [[XMPPRoster alloc]initWithRosterStorage:rosterCoreDataStorage dispatchQueue:dispatch_get_main_queue()]; 
    5. //激活 
    6.    [self.xmppRoster activate:self.xmppStream]; 
    7. //設(shè)置代理 
    8.   [self.xmppRoster addDelegate:self delegateQueue:dispatch_get_main_queue()]; 
  2. 接收好友請求。
    將接收到好友請求的方法也封裝在XMPPManager中:

    1. // 收到好友請求執(zhí)行的方法 
    2. -(void)xmppRoster:(XMPPRoster )sender didReceivePresenceSubscriptionRequest:(XMPPPresence )presence{ 
    3.  self.fromJid = presence.from; 
    4.  UIAlertView alert = [[UIAlertView alloc]initWithTitle:@"提示:有人添加你" message:presence.from.user  delegate:self cancelButtonTitle:@"拒絕" otherButtonTitles:@"OK", nil]; 
    5.  [alert show]; 
    1. -(void)alertView:(UIAlertView )alertView clickedButtonAtIndex:(NSInteger)buttonIndex{ 
    2.   switch (buttonIndex) { 
    3.    case 0
    4.    [self.xmppRoster rejectPresenceSubscriptionRequestFrom:self.fromJid]; 
    5.   break
    6.    case 1
    7.    [self.xmppRoster acceptPresenceSubscriptionRequestFrom:self.fromJid andAddToRoster:YES]; 
    8.    break
    9.    default
    10.    break
    11.  } 
  3. 添加好友,添加的好友必須是服務(wù)器上存在的用戶,需要看對方是否同意。對方同意之后,刷新好友列表,顯示出來,同時(shí)在服務(wù)器上也要添加,這里服務(wù)器上用的是coredata來存儲個人的好友信息。

好友頁面實(shí)現(xiàn)文件,遵循代理,數(shù)據(jù)源數(shù)組

在viewDidLoad中完成初始化數(shù)組,設(shè)置代理和添加好友按鈕

這里簡化了添加好友,寫死了只能添加“張三”,如果需要添加更多,可以寫成借口

接下來是tableview數(shù)據(jù)源代理方法

tableview

這時(shí)候數(shù)組明顯是沒有jid對象的。獲取jid對象是在XMPPPRoster代理方法中實(shí)現(xiàn)的:

pragma mark xmppRoster 的代理方法

  1. pragma mark 開始檢索好友列表的方法 
  2. -(void)xmppRosterDidBeginPopulating:(XMPPRoster *)sender{ 
  3.     NSLog(@"開始檢索好友列表"); 
  1. pragma mark 正在檢索好友列表的方法 
  2. -(void)xmppRoster:(XMPPRoster )sender didRecieveRosterItem:(DDXMLElement )item{ 
  3.     NSLog(@"每一個好友都會走一次這個方法"); 
  4. //獲得item的屬性里的jid字符串,再通過它獲得jid對象 
  5.     NSString jidStr = [[item attributeForName:@"jid"] stringValue]; 
  6.     XMPPJID jid = [XMPPJID jidWithString:jidStr]; 
  7. //是否已經(jīng)添加 
  8.     if ([self.rosterJids containsObject:jid]) { 
  9.         return
  10.     } 
  11. //將好友添加到數(shù)組中去 
  12.     [self.rosterJids addObject:jid]; 
  13. //添加完數(shù)據(jù)要更新UI(表視圖更新) 
  14.     NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.rosterJids.count-1 inSection:0]; 
  15.     [self.tableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic]; 
  1. pragma mark 好友列表檢索完畢的方法 
  2. -(void)xmppRosterDidEndPopulating:(XMPPRoster )sender{ 
  3.     NSLog(@"好友列表檢索完畢"); 

4. 刪除好友。列表刪除,數(shù)組刪除,服務(wù)器刪除。

  1. pragma mark 刪除好友執(zhí)行的方法 
  2. -(void)tableView:(UITableView )tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath )indexPath{ 
  3.     if (editingStyle==UITableViewCellEditingStyleDelete) { 
  4.  //找到要刪除的人 
  5.         XMPPJID jid = self.rosterJids[indexPath.row]; 
  6. //從數(shù)組中刪除 
  7.         [self.rosterJids removeObjectAtIndex:indexPath.row]; 
  8. //從Ui單元格刪除 
  9.         [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic 
  10.          ]; 
  11. //從服務(wù)器刪除 
  12.         [[XMPPManager defaultManager].xmppRoster removeUser:jid]; 
  13.     } 

5.進(jìn)入聊天頁面

點(diǎn)擊進(jìn)入聊天頁面的方法

聊天頁面接受jid值的屬性

聊天

1.發(fā)送普通文本消息
同樣在XMPPManager中進(jìn)行封裝;

  1. //聊天信息歸檔 
  2. @property(nonatomic,strong)XMPPMessageArchiving xmppMessageArchiving; 
  3. //信息歸檔的上下文 
  4. @property(nonatomic,strong)NSManagedObjectContext messageArchivingContext; 

在init初始化時(shí):

  1. //3.保存聊天記錄 
  2.   //初始化一個倉庫 
  3.         XMPPMessageArchivingCoreDataStorage *messageStorage = [XMPPMessageArchivingCoreDataStorage sharedInstance]; 
  4.   //創(chuàng)建一個消息歸檔對象 
  5.         self.xmppMessageArchiving = [[XMPPMessageArchiving alloc]initWithMessageArchivingStorage:messageStorage dispatchQueue:dispatch_get_main_queue()]; 
  6.   //激活 
  7.         [self.xmppMessageArchiving activate:self.xmppStream]; 
  8.   //上下文 
  9.         self.messageArchivingContext = messageStorage.mainThreadManagedObjectContext; 

在聊天頁面的viewDidload中:

發(fā)送普通消息:

  1. -(void)doSend{ 
  2.     //創(chuàng)建一個消息對象,并且指明接收者 
  3.     XMPPMessage *message = [XMPPMessage messageWithType:@"chat" to:self.chatToJid]; 
  4.     //設(shè)置消息內(nèi)容 
  5.     [message addBody:@"呵呵呵呵呵呵呵呵呵呵"]; 
  6.     //發(fā)送消息 
  7.     [[XMPPManager defaultManager].xmppStream sendElement:message]; 
  8.     //發(fā)送成功或者失敗,有兩種對應(yīng)的代理方法 

消息發(fā)送是否成功,會走下面的代理方法:

xmppStream的代理方法

刷新消息的方法,需要熟悉CoreData知識
#pragma mark 刷新消息的方法
-(void)reloadMessage{
//得到上下文
NSManagedObjectContext context = [XMPPManager defaultManager].messageArchivingContext;
//搜索對象
NSFetchRequest request = [[NSFetchRequest alloc]init];
//創(chuàng)建一個實(shí)體描述
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.顯示聊天記錄

  1. - (NSInteger)tableView:(UITableView )tableView numberOfRowsInSection:(NSInteger)section { 
  2.     return self.messages.count; 
  1. - (UITableViewCell )tableView:(UITableView )tableView cellForRowAtIndexPath:(NSIndexPath )indexPath { 
  2.     static NSString cellIndentifier = @"cell"
  3.     UITableViewCell cell = [tableView dequeueReusableCellWithIdentifier:cellIndentifier]; 
  4.     if (cell==nil) { 
  5.      cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellIndentifier]; 
  6.     } 
  7.    //將聊天信息放到cell上 
  8.     //拿到一個聊天消息 
  9.     XMPPMessageArchiving_Message_CoreDataObject message = self.messages[indexPath.row]; 
  10.     if (message.isOutgoing == YES) { 
  11.      cell.detailTextLabel.text = message.body; 
  12.      } 
  13.     }else
  14.      cell.textLabel.text = message.body; 
  15.     } 
  16.     return cell; 

成功后就可以聊天了:

演示圖

 3.發(fā)送圖片等消息(重點(diǎn))
發(fā)送視頻等其他文件也是一樣,xmpp中需要將圖片轉(zhuǎn)化成NSData,然后轉(zhuǎn)化成成base64的字符串進(jìn)行傳輸,然后接收到之后再反轉(zhuǎn)化成圖片。
首先要訪問系統(tǒng)相冊。
遵循代理:

  1. @interface ChatViewController ()<XMPPStreamDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate> 

從系統(tǒng)相冊選擇照片

發(fā)送圖片消息

這時(shí)候需要更改cellForRowAtIndexPath:方法,注意紅色部分。

發(fā)送圖片消息對應(yīng)cell里也需要更改

我把圖片設(shè)置為cell的imageView,所以圖片顯示了在左邊,說明圖片消息發(fā)送是成功的,視頻等其他類型的消息,也是同樣的原理。

圖片消息演示

到這里,簡單的聊天功能就實(shí)現(xiàn)了,了解了基本原理和操作,我們自己還可以加入更多的自定義,從而優(yōu)化得更好。這里僅僅講述了一些基本的方法,如果想了解更多,趕快自己動手實(shí)踐吧

責(zé)任編輯:倪明 來源: 簡書
相關(guān)推薦

2015-07-06 10:42:18

PHP聊天室應(yīng)用

2016-08-23 13:53:25

iOS開發(fā)邏輯

2009-05-20 14:49:16

ibmdwAjaxWeb開發(fā)

2012-06-21 17:37:57

2020-12-14 06:48:42

Redis記錄轉(zhuǎn)存

2021-09-08 14:54:51

微信功能備份

2021-08-12 07:24:42

WhatsAppAndroidiOS

2023-05-11 15:12:12

2011-04-06 16:14:40

Delphi

2023-05-20 11:17:05

必應(yīng)聊天微軟

2018-01-04 13:53:43

技術(shù)命令windows

2019-06-04 08:00:00

機(jī)器人聊天機(jī)器人人工智能

2021-10-08 15:31:24

機(jī)器人人工智能編程

2020-08-25 15:17:12

戴爾

2021-09-06 08:50:49

服務(wù)Dubbo參數(shù)

2024-07-31 09:55:19

2020-04-13 17:26:42

微信Bug修復(fù)

2023-01-13 00:02:41

2023-01-05 09:17:58

2023-06-19 08:36:30

頻率setData元素
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號