基於XMPP的IOS聊天客戶端程序

簡介:XMPP協議是一種基於Socket長鏈接、以XML格式進行基本信息交換、C/S S/S多種架構的聊天協議
XMPPServer 基於XMPP協議的服務端(例如eJabber、OpenFire)
openfire服務器安裝和配置鏈接地址: http://www.cnblogs.com/hoojo/archive/2012/05/17/2506769.htmlhtml

一.框架導入

1.在header search Path 中 添加 /user/include/libxml2

2.添加libxml2.dylib與libresolv.dylib

3.拷貝源碼目錄下的 Authentication Categories Core 和 Utilities 到項目根目錄下並添加到項目中

二.核心庫

1.XMPPStream 核心中的核心:xml流

2.XMPPElement xml基本元素/stanza

3.XMPPIQ 查詢節點 Info/Query的縮寫 相似於HTTP請求

4.XMPPJID 用戶的標識/身份證

5.XMPPMessage 基本消息節點(XML)

6.XMPPPresence 出席節點(XML)

7.XMPPParser XML解析,Core中惟一一個不過重要的類

8.XMPPModule 各類功能模塊的基類,繼承它的模塊均需在xmppStream中激活,基於多播代理,可添加多個委託實例

三.擴展庫

1.XMPPRoster好友列表
2.XMPPReconnect重連
3.ProcessOne推送通知與快速重連
4.XMPPBandwidthMonitor 帶寬監視
5.XMPPFileTransfer文件傳輸
6.XMPPRoom(XEP-0045)聊天室
7.XMPPvCard(XEP--0054)我的資料/名片
8.XMPPResultSet(XEP-0059)XML中的結果集
9.XMPPPubSub(XEP-0060) 發佈/訂閱模塊
10.XMPPRegistration(XEP-0077)註冊與密碼修改
11.XMPPMessage+XEP_0085消息節點的聊天狀態擴展
12.XMPPMessageArchiving(XEP-0136)聊天記錄同步
13.XMPPMessageDeliveryReceipts(XEP-0184)接受消息回執
14.XMPPBlocking(XEP-0191)黑名單/屏蔽用戶
15.XMPPStreamManagement(XEP-0198)XML流恢復(區別於Reconnect)
16.XMPPAutoPing(XEP-0199)心跳檢測
17.XMPPAutoTime(XEP-0202)時間比對
18.NSXMLElement+XEP_0203(DelayedMessage)延遲消息
19.XMPPAttentionModule(XEP-0224)引發對方注意的消息模塊,需激活
20.XMPPMessageCarbons(XEP-0280)同一個用戶多設備登錄(jid的資源部分不一樣)時的消息多發
21.NSXMLElement+XEP_0297 XML節點擴展--消息轉發
22.XMPPMessage+XEP_0308一種特殊消息:對已經發送的某條消息進行更改/訂正
23.XMPPMessage+XEP_0333更佳先進的消息回執 Message的分類
24.XMPPElement+JSON(XEP-0335)在XML節點中插入JSONjava

四.xmpp創建鏈接並登陸

1.新建一個 XMPPStream 對象,添加委託

添加委託方法 - (void)addDelegate:(id)delegate delegateQueue:(dispatch_queue_t)delegateQueue
參數 delegateQueue 爲委託回調所使用的 GCD 隊列,dispatch_get_main_queue() 獲取主線程 GCD 隊列數據庫

2.XMPPJid

JID 通常由三部分構成:用戶名,域名和資源名,例如 test@example.com/Anthony 若是沒有設置主機名,則使用 JID 的域名做爲主機名 端口號是可選的,默認是 5222緩存

3.身份認證

實現 - (void)xmppStreamDidConnect:(XMPPStream )sender 委託方法
鏈接服務器成功後,回調該方法
身份認證方法 - (BOOL)authenticateWithPassword:(NSString
)inPassword error:(NSError **)errPtr服務器

4.上線

實現 - (void)xmppStreamDidAuthenticate:(XMPPStream *)sender 委託方法 身份認證成功後,回調該方法 新建一個 XMPPPresence 對象,類型爲 available,發送!架構

5.退出並斷開鏈接

新建一個 XMPPPresence 對象,類型爲 unavailable,發送!
斷開鏈接app

五.XMPP註冊

1.判斷xmpp否鏈接,是否帶註冊支持

[[self appDelegate] xmppStream] isConnected] && [[[self appDelegate]xmppStream] supportsInBandRegistration]框架

2.開始註冊

設置myjid和密碼 1.setMyJID 2.registerWithPasswordide

六.好友列表

1. 獲取好友列表

注意本地數據庫緩存 NSManagedObjectContext context = [[[self appDelegate] xmppRosterStorage] mainThreadManagedObjectContext];
NSEntityDescription
entity = [NSEntityDescription entityForName:@"XMPPUserCoreDataStorageObject" inManagedObjectContext:context]; NSFetchRequest request = [[NSFetchRequest alloc]init];
[request setEntity:entity];
NSError
error ;
NSArray *friends = [context executeFetchRequest:request error:&error];ui

2.對方添加好友時 更新列表 // 已經互爲好友之後,會回調此

  • (void)xmppRoster:(XMPPRoster )sender didReceiveRosterItem:(NSXMLElement )item {
    NSString *subscription = [item attributeStringValueForName:@"subscription"];
    if ([subscription isEqualToString:@"both"]) {
    NSLog(@"雙方已經互爲好友");
    if (self.buddyListBlock) {
    // 更新好友列表
    }
    }
    }

七.xmpp添加好友

[[[self appDelegate] xmppRoster] addUser:[XMPPJID jidWithString:@"admin@127.0.0.1"] withNickname:@"admin"];

八.xmpp發送消息和接收消息

1.發送消息

咱們須要根據 XMPP 協議,將數據放到 標籤內,例如:

Hello World!

  • (void)sendMessage:(NSString ) message toUser:(NSString ) user {
    NSXMLElement body = [NSXMLElement elementWithName:@"body"];
    [body setStringValue:message];
    NSXMLElement
    message = [NSXMLElement elementWithName:@"message"];
    [message addAttributeWithName:@"type" stringValue:@"chat"];
    NSString *to = [NSString stringWithFormat:@"%@@example.com", user];
    [message addAttributeWithName:@"to" stringValue:to];
    [message addChild:body];
    [self.xmppStream sendElement:message];
    }

2.接收消息

當接收到 標籤的內容時,XMPPFramework 框架回調該方法
根據 XMPP 協議,消息體的內容存儲在標籤 內

  • (void)xmppStream:(XMPPStream )sender didReceiveMessage:(XMPPMessage )message {

    NSString *messageBody = [[message elementForName:@"body"] stringValue];

}

爲了方便程序調用,咱們把XMPP的一些主要方法寫在AppDelegate中

在AppDelegate.m下這幾個方法爲:

```objectc
-(void)setupStream{

//初始化XMPPStream  
xmppStream = [[XMPPStream alloc] init]; 
[xmppStream addDelegate:self delegateQueue:dispatch_get_current_queue()];

}

-(void)goOnline{

//發送在線狀態  
XMPPPresence *presence = [XMPPPresence presence]; 
[[self xmppStream] sendElement:presence];

}

-(void)goOffline{

//發送下線狀態  
XMPPPresence *presence = [XMPPPresence presenceWithType:@"unavailable"]; 
[[self xmppStream] sendElement:presence];

}

-(BOOL)connect{

[self setupStream]; 
 
//從本地取得用戶名,密碼和服務器地址  
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; 
 
NSString *userId = [defaults stringForKey:USERID]; 
NSString *pass = [defaults stringForKey:PASS]; 
NSString *server = [defaults stringForKey:SERVER]; 
 
if (![xmppStream isDisconnected]) { 
    return YES; 
} 
 
if (userId == nil || pass == nil) { 
    return NO; 
} 
 
//設置用戶  
[xmppStream setMyJID:[XMPPJID jidWithString:userId]]; 
//設置服務器  
[xmppStream setHostName:server]; 
//密碼  
password = pass; 
 
//鏈接服務器  
NSError *error = nil; 
if (![xmppStream connect:&error]) { 
    NSLog(@"cant connect %@", server); 
    return NO; 
} 
 
return YES;

}

-(void)disconnect{

[self goOffline]; 
[xmppStream disconnect];

}

-(void)setupStream{

//初始化XMPPStream
xmppStream = [[XMPPStream alloc] init];
[xmppStream addDelegate:self delegateQueue:dispatch_get_current_queue()];

}

-(void)goOnline{

//發送在線狀態
XMPPPresence *presence = [XMPPPresence presence];
[[self xmppStream] sendElement:presence];

}

-(void)goOffline{

//發送下線狀態
XMPPPresence *presence = [XMPPPresence presenceWithType:@"unavailable"];
[[self xmppStream] sendElement:presence];

}

-(BOOL)connect{

[self setupStream];

//從本地取得用戶名,密碼和服務器地址
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

NSString *userId = [defaults stringForKey:USERID];
NSString *pass = [defaults stringForKey:PASS];
NSString *server = [defaults stringForKey:SERVER];

if (![xmppStream isDisconnected]) {
    return YES;
}

if (userId == nil || pass == nil) {
    return NO;
}

//設置用戶
[xmppStream setMyJID:[XMPPJID jidWithString:userId]];
//設置服務器
[xmppStream setHostName:server];
//密碼
password = pass;

//鏈接服務器
NSError *error = nil;
if (![xmppStream connect:&error]) {
    NSLog(@"cant connect %@", server);
    return NO;
}

return YES;

}

-(void)disconnect{

[self goOffline];
[xmppStream disconnect];

}這幾個是基礎方法,接下來就是XMPPStreamDelegate中的方法,也是接受好友狀態,接受消息的重要方法

[objectc]
//鏈接服務器

  • (void)xmppStreamDidConnect:(XMPPStream *)sender{

    isOpen = YES;
    NSError *error = nil;
    //驗證密碼
    [[self xmppStream] authenticateWithPassword:password error:&error];

}

//驗證經過

  • (void)xmppStreamDidAuthenticate:(XMPPStream *)sender{

    [self goOnline];
    }

//收到消息

  • (void)xmppStream:(XMPPStream )sender didReceiveMessage:(XMPPMessage )message{

// NSLog(@"message = %@", message);

NSString *msg = [[message elementForName:@"body"] stringValue]; 
NSString *from = [[message attributeForName:@"from"] stringValue]; 
 
NSMutableDictionary *dict = [NSMutableDictionary dictionary]; 
[dict setObject:msg forKey:@"msg"]; 
[dict setObject:from forKey:@"sender"]; 
 
//消息委託(這個後面講)  
[messageDelegate newMessageReceived:dict];

}

//收到好友狀態

  • (void)xmppStream:(XMPPStream )sender didReceivePresence:(XMPPPresence )presence{

// NSLog(@"presence = %@", presence);

//取得好友狀態  
NSString *presenceType = [presence type]; //online/offline  
//當前用戶  
NSString *userId = [[sender myJID] user]; 
//在線用戶  
NSString *presenceFromUser = [[presence from] user]; 
 
if (![presenceFromUser isEqualToString:userId]) { 
     
    //在線狀態  
    if ([presenceType isEqualToString:@"available"]) { 
         
        //用戶列表委託(後面講)  
        [chatDelegate newBuddyOnline:[NSString stringWithFormat:@"%@@%@", presenceFromUser, @"nqc1338a"]]; 
         
    }else if ([presenceType isEqualToString:@"unavailable"]) { 
        //用戶列表委託(後面講)  
        [chatDelegate buddyWentOffline:[NSString stringWithFormat:@"%@@%@", presenceFromUser, @"nqc1338a"]]; 
    } 
     
}

}

//鏈接服務器

  • (void)xmppStreamDidConnect:(XMPPStream *)sender{

    isOpen = YES;
    NSError *error = nil;
    //驗證密碼
    [[self xmppStream] authenticateWithPassword:password error:&error];

}

//驗證經過

  • (void)xmppStreamDidAuthenticate:(XMPPStream *)sender{

    [self goOnline];
    }

//收到消息

  • (void)xmppStream:(XMPPStream )sender didReceiveMessage:(XMPPMessage )message{

// NSLog(@"message = %@", message);

NSString *msg = [[message elementForName:@"body"] stringValue];
NSString *from = [[message attributeForName:@"from"] stringValue];

NSMutableDictionary *dict = [NSMutableDictionary dictionary];
[dict setObject:msg forKey:@"msg"];
[dict setObject:from forKey:@"sender"];

//消息委託(這個後面講)
[messageDelegate newMessageReceived:dict];

}

//收到好友狀態

  • (void)xmppStream:(XMPPStream )sender didReceivePresence:(XMPPPresence )presence{

// NSLog(@"presence = %@", presence);

//取得好友狀態
NSString *presenceType = [presence type]; //online/offline
//當前用戶
NSString *userId = [[sender myJID] user];
//在線用戶
NSString *presenceFromUser = [[presence from] user];

if (![presenceFromUser isEqualToString:userId]) {
   
    //在線狀態
    if ([presenceType isEqualToString:@"available"]) {
       
        //用戶列表委託(後面講)
        [chatDelegate newBuddyOnline:[NSString stringWithFormat:@"%@@%@", presenceFromUser, @"nqc1338a"]];
       
    }else if ([presenceType isEqualToString:@"unavailable"]) {
        //用戶列表委託(後面講)
        [chatDelegate buddyWentOffline:[NSString stringWithFormat:@"%@@%@", presenceFromUser, @"nqc1338a"]];
    }
   
}

}
這裏面有兩個委託方法,一個是用戶列表委託,還有一個就是消息委託,用戶列表委託主要就是取得在線用戶,更新用戶TableView,消息委託就是取得好友發送的消息,並更新消息TableView,固然這兩個TableView是在不一樣的Controller中的

定義完兩個委託,咱們就要在不一樣的Controller中實現這兩個委託了

在好友Controller中實現 並寫入以下方法

[java]
//取得當前程序的委託
-(KKAppDelegate *)appDelegate{

return (KKAppDelegate *)[[UIApplication sharedApplication] delegate];

}

//取得當前的XMPPStream
-(XMPPStream *)xmppStream{

return [[self appDelegate] xmppStream];

}

//在線好友
-(void)newBuddyOnline:(NSString *)buddyName{

if (![onlineUsers containsObject:buddyName]) { 
    [onlineUsers addObject:buddyName]; 
    [self.tView reloadData]; 
}

}

//好友下線
-(void)buddyWentOffline:(NSString *)buddyName{

[onlineUsers removeObject:buddyName]; 
[self.tView reloadData];

}

//取得當前程序的委託
-(KKAppDelegate *)appDelegate{

return (KKAppDelegate *)[[UIApplication sharedApplication] delegate];

}

//取得當前的XMPPStream
-(XMPPStream *)xmppStream{

return [[self appDelegate] xmppStream];

}

//在線好友
-(void)newBuddyOnline:(NSString *)buddyName{

if (![onlineUsers containsObject:buddyName]) {
    [onlineUsers addObject:buddyName];
    [self.tView reloadData];
}

}

//好友下線
-(void)buddyWentOffline:(NSString *)buddyName{

[onlineUsers removeObject:buddyName];
[self.tView reloadData];

}
在viewDidLoad中加入

[java]
//設定在線用戶委託
KKAppDelegate *del = [self appDelegate];
del.chatDelegate = self;

//設定在線用戶委託
KKAppDelegate *del = [self appDelegate];
del.chatDelegate = self;這兩行代碼,讓好友列表的委託實現方法在本程序中

在viewWillAppear中加入

[java]
[super viewWillAppear:animated];

NSString *login = [[NSUserDefaults standardUserDefaults] objectForKey:@"userId"];

if (login) {

if ([[self appDelegate] connect]) { 
    NSLog(@"show buddy list"); 
     
}

}else {

//設定用戶  
[self Account:self];

}

[super viewWillAppear:animated];

NSString *login = [[NSUserDefaults standardUserDefaults] objectForKey:@"userId"];

if (login) {
   
    if ([[self appDelegate] connect]) {
        NSLog(@"show buddy list");
       
    }
   
}else {
   
    //設定用戶
    [self Account:self];
   
}

判斷本地保存的數據中是否有userId,沒有的話就跳轉到登陸頁面

這裏最重要的就是connect了,這一句話就是登陸了,成功的話,頁面就會顯示好友列表了。

[java]

pragma mark UITableViewDelegate

-(void)tableView:(UITableView )tableView didSelectRowAtIndexPath:(NSIndexPath )indexPath{

//start a Chat  
chatUserName = (NSString *)[onlineUsers objectAtIndex:indexPath.row]; 
 
[self performSegueWithIdentifier:@"chat" sender:self];

}
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{

if ([segue.identifier isEqualToString:@"chat"]) { 
    KKChatController *chatController = segue.destinationViewController; 
    chatController.chatWithUser = chatUserName; 
}

}

pragma mark UITableViewDelegate

-(void)tableView:(UITableView )tableView didSelectRowAtIndexPath:(NSIndexPath )indexPath{

//start a Chat
chatUserName = (NSString *)[onlineUsers objectAtIndex:indexPath.row];

[self performSegueWithIdentifier:@"chat" sender:self];

}
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{

if ([segue.identifier isEqualToString:@"chat"]) {
    KKChatController *chatController = segue.destinationViewController;
    chatController.chatWithUser = chatUserName;
}

}
當顯示出好友列表,咱們選擇一個好友進行聊天

將當前好友名稱發送給聊天頁面

下面是聊天Controller了

在KKChatController.h中加入

[java]
NSMutableArray *messages;

NSMutableArray *messages;這是咱們要顯示的消息,每一條消息爲一條字典

接下來就是每一條消息的顯示了

[java]
-(UITableViewCell )tableView:(UITableView )tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

static NSString *identifier = @"msgCell"; 
 
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier]; 
 
if (cell == nil) { 
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier]; 
} 
 
NSMutableDictionary *dict = [messages objectAtIndex:indexPath.row]; 
 
cell.textLabel.text = [dict objectForKey:@"msg"]; 
cell.detailTextLabel.text = [dict objectForKey:@"sender"]; 
cell.accessoryType = UITableViewCellAccessoryNone; 
 
return cell;

}

-(UITableViewCell )tableView:(UITableView )tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

static NSString *identifier = @"msgCell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];

if (cell == nil) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier];
}

NSMutableDictionary *dict = [messages objectAtIndex:indexPath.row];

cell.textLabel.text = [dict objectForKey:@"msg"];
cell.detailTextLabel.text = [dict objectForKey:@"sender"];
cell.accessoryType = UITableViewCellAccessoryNone;

return cell;

}
跟上面好友Controller同樣,這裏咱們也須要XMPPStream

[java]
-(KKAppDelegate *)appDelegate{

return (KKAppDelegate *)[[UIApplication sharedApplication] delegate];

}

-(XMPPStream *)xmppStream{

return [[self appDelegate] xmppStream];

}

-(KKAppDelegate *)appDelegate{

return (KKAppDelegate *)[[UIApplication sharedApplication] delegate];

}

-(XMPPStream *)xmppStream{

return [[self appDelegate] xmppStream];

}
在ViewDidLoad中加入

[java]
KKAppDelegate *del = [self appDelegate];
del.messageDelegate = self;

KKAppDelegate *del = [self appDelegate];
del.messageDelegate = self;
設定消息委託由本身來接收和處理

pragma mark KKMessageDelegate

···objectc
-(void)newMessageReceived:(NSDictionary *)messageCotent{

[messages addObject:messageCotent]; 
 
[self.tView reloadData];

}

pragma mark KKMessageDelegate

-(void)newMessageReceived:(NSDictionary *)messageCotent{

[messages addObject:messageCotent];

[self.tView reloadData];

}

接下來最重要的就是發送消息了

  • (IBAction)sendButton:(id)sender {

    //本地輸入框中的信息
    NSString *message = self.messageTextField.text;

    if (message.length > 0) {

    //XMPPFramework主要是經過KissXML來生成XML文件  
      //生成<body>文檔  
      NSXMLElement *body = [NSXMLElement elementWithName:@"body"]; 
      [body setStringValue:message]; 
    
      //生成XML消息文檔  
      NSXMLElement *mes = [NSXMLElement elementWithName:@"message"]; 
      //消息類型  
      [mes addAttributeWithName:@"type" stringValue:@"chat"]; 
      //發送給誰  
      [mes addAttributeWithName:@"to" stringValue:chatWithUser]; 
      //由誰發送  
      [mes addAttributeWithName:@"from" stringValue:[[NSUserDefaults standardUserDefaults] stringForKey:USERID]]; 
      //組合  
      [mes addChild:body]; 
    
      //發送消息  
      [[self xmppStream] sendElement:mes]; 
    
      self.messageTextField.text = @""; 
      [self.messageTextField resignFirstResponder]; 
    
      NSMutableDictionary *dictionary = [NSMutableDictionary dictionary]; 
    
      [dictionary setObject:message forKey:@"msg"]; 
      [dictionary setObject:@"you" forKey:@"sender"]; 
    
      [messages addObject:dictionary]; 
    
      //從新刷新tableView  
      [self.tView reloadData];

    }

}

相關文章
相關標籤/搜索