你好,歡迎來到IOS教程網

 Ios教程網 >> IOS訊息 >> 關於IOS >> [iPhone高級] 基於XMPP的IOS聊天客戶端程序

[iPhone高級] 基於XMPP的IOS聊天客戶端程序

編輯:關於IOS

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

 /

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

[java]
-(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中的方法,也是接受好友狀態,接受消息的重要方法

[java]
//連接服務器  
- (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中實現<KKChatDelegate>並寫入如下方法

[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;
設定消息委托由自己來接收和處理

[java]
#pragma mark KKMessageDelegate 
-(void)newMessageReceived:(NSDictionary *)messageCotent{ 
     
    [messages addObject:messageCotent]; 
     
    [self.tView reloadData]; 
     

#pragma mark KKMessageDelegate
-(void)newMessageReceived:(NSDictionary *)messageCotent{
   
    [messages addObject:messageCotent];
   
    [self.tView reloadData];
   
}接下來最重要的就是發送消息了

[java]
- (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]; 
         
    } 
     
     

- (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];
       
    }
   
   
}上面都加了注釋,大家應該能明白,接下來還有一個章節,我們會對發送的消息在界面進行美化,跟蘋果自帶的消息一樣。謝謝大家有耐心看完,我這個人比較不喜歡打字,所以有的地方注釋比較少,希望大家別介意,還有希望大家能夠多多支持, 以後會接著介紹XMPP文件傳輸之類的內容。
作者:kangkangz4
 

  1. 上一頁:
  2. 下一頁:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © Ios教程網 All Rights Reserved