iPhone平台下基于XMPP的IM研究-登入部分

    怎样将XMPPFramework添加到我们自己的项目中,请参考 http://kongkongbrain.blog.163.com/blog/static/17819901320114235295322/ ,感谢这位兄弟,因为网上关于这个框架的使用文章太少了。

     代码步骤:

1、初始化XMPPStream 

xmppStream = [[XMPPStream allocinit];

xmppStream.hostName = @"127.0.0.1";

xmppStream.hostPort = 5222;

[xmppStreamaddDelegate:selfdelegateQueue:dispatch_get_main_queue()];

XmppFramework的消息监听方式使用delegate。在smack中我们使用的是listener,其实都一样。


2、设置JID;(注意JID的Domain一定要用主机名,不要用IP地址。我的疏忽让我晚上熬到了3点多)

xmppStream.myJID = [XMPPJID jidWithString:[NSString stringWithFormat:@"%@@liu-lavymatoMacBook-Pro.local",myJID]];

3、连接服务器

NSError *error = nil;

[xmppStream connect:&error];

接下来就是一系列依次调用delegate的方法

xmppStreamWillConnect

socketDidConnect

xmppStreamDidConnect 在这个方法中我们需要调用:         [xmppStreamauthenticateWithPassword:myPassworderror:&error]

验证成功:xmppStreamDidAuthenticate:

验证失败:xmppStream: didNotAuthenticate:


[cpp]  view plain copy
  1. //  
  2. //  XmppTest1AppDelegate.h  
  3. //  XmppTest1  
  4. //  
  5. //  Created by liu lavy on 11-10-2.  
  6. //  Copyright 2011 __MyCompanyName__. All rights reserved.  
  7. //  
  8.   
  9. #import <UIKit/UIKit.h>  
  10. #import "XMPPFramework.h"  
  11.   
  12. @class XmppTest1ViewController;  
  13.   
  14. @interface XmppTest1AppDelegate : NSObject <UIApplicationDelegate, XMPPRosterDelegate> {  
  15.     UIWindow *window;  
  16.     XmppTest1ViewController *viewController;  
  17.     XMPPStream *xmppStream;  
  18.     XMPPReconnect *xmppReconnect;  
  19.     NSString *myPassword;  
  20. }  
  21.   
  22. @property (nonatomic, retain) IBOutlet UIWindow *window;  
  23. @property (nonatomic, retain) IBOutlet XmppTest1ViewController *viewController;  
  24.   
  25. @property (nonatomic, retain) XMPPStream *xmppStream;  
  26. @property (nonatomic, readonly) XMPPReconnect *xmppReconnect;  
  27. @property (nonatomic, retain) NSString *myPassword;  
  28.   
  29.   
  30. -(BOOL) connect:(NSString *)myJID password:(NSString *)myPassword;  
  31. -(BOOL) authenticate;  
  32. -(void) disConnect;  
  33. @end  


[cpp]  view plain copy
  1. //  
  2. //  XmppTest1AppDelegate.m  
  3. //  XmppTest1  
  4. //  
  5. //  Created by liu lavy on 11-10-2.  
  6. //  Copyright 2011 __MyCompanyName__. All rights reserved.  
  7. //  
  8.   
  9. #import "XmppTest1AppDelegate.h"  
  10. #import "XmppTest1ViewController.h"  
  11. #import "DDLog.h"  
  12. #import "DDTTYLogger.h"  
  13.   
  14. #if DEBUG  
  15. static const int ddLogLevel = LOG_LEVEL_VERBOSE;  
  16. #else  
  17. static const int ddLogLevel = LOG_LEVEL_VERBOSE;  
  18. #endif  
  19.   
  20. @interface XmppTest1AppDelegate(PrivateMethod)  
  21. -(void) setupStream;  
  22. -(void) teardownStream;  
  23. @end  
  24.   
  25. @implementation XmppTest1AppDelegate  
  26.   
  27. @synthesize window;  
  28. @synthesize viewController;  
  29. @synthesize xmppStream;  
  30. @synthesize xmppReconnect;  
  31. @synthesize myPassword;  
  32.   
  33. #pragma mark -  
  34. #pragma mark Application lifecycle  
  35.   
  36. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {      
  37.     [DDLog addLogger:[DDTTYLogger sharedInstance]];  
  38.   
  39.     self.window.rootViewController = self.viewController;  
  40.     [self.window makeKeyAndVisible];  
  41.       
  42.     [self setupStream];  
  43.     return YES;  
  44. }  
  45.   
  46. -(void) setupStream {  
  47.     NSAssert(xmppStream == nil, @"Method setupStream invoked multiple times");  
  48.     xmppStream = [[XMPPStream alloc] init];  
  49.     xmppReconnect = [[XMPPReconnect alloc] init];  
  50.     [xmppReconnect activate:xmppStream];  
  51.       
  52.     [xmppStream addDelegate:self delegateQueue:dispatch_get_main_queue()];  
  53.     [xmppReconnect addDelegate:self delegateQueue:dispatch_get_main_queue()];  
  54.       
  55.     xmppStream.hostName = @"127.0.0.1";  
  56.     xmppStream.hostPort = 5222;  
  57. }  
  58.   
  59. -(void) teardownStream {  
  60.     [xmppStream removeDelegate:self];  
  61.     [xmppReconnect deactivate];  
  62.     [xmppStream disconnect];  
  63.     xmppStream = nil;  
  64.     xmppReconnect = nil;  
  65. }  
  66.   
  67. -(BOOL) connect:(NSString *)myJID password:(NSString *)password {  
  68.     if([xmppStream isConnected]) {  
  69.         [self disConnect];  
  70.     }  
  71.     self.myPassword = password;  
  72.     if(!myPassword|| [myPassword length] == 0) {  
  73.         UIAlertView *alertViewValidate = [[UIAlertView alloc] initWithTitle:@"连接失败"   
  74.                                                                     message:@"密码不能为空"   
  75.                                                                    delegate:nil  
  76.                                                           cancelButtonTitle:@"OK"   
  77.                                                           otherButtonTitles:nil];  
  78.         [alertViewValidate show];  
  79.         [alertViewValidate release];  
  80.         return NO;  
  81.     }  
  82.       
  83.     NSError *error = nil;  
  84.     XMPPJID *myXmppJID = [XMPPJID jidWithString:[NSString stringWithFormat:@"%@@liu-lavymatoMacBook-Pro.local",myJID]];  
  85.     //XMPPJID *myXmppJID = [XMPPJID jidWithString:@"test1@liu-lavymatoMacBook-Pro.local"];  
  86.     xmppStream.myJID = myXmppJID;  
  87.     //NSLog(@"%@", [NSString stringWithFormat:@"%d",[xmppStream connect:&error]]);  
  88.     if(![xmppStream connect:&error]) {  
  89.         UIAlertView *alertViewFailedConn = [[UIAlertView alloc] initWithTitle:@"连接失败"   
  90.                                                                       message:@"详细请查看控制台"   
  91.                                                                      delegate:nil  
  92.                                                             cancelButtonTitle:@"OK"  
  93.                                                             otherButtonTitles:nil];  
  94.         [alertViewFailedConn show];  
  95.         [alertViewFailedConn release];  
  96.         DDLogError(@"Error connecting: %@", error);  
  97.         return NO;  
  98.     }  
  99.     DDLogVerbose(@"连接成功");  
  100.     return YES;  
  101. }  
  102.   
  103. -(BOOL) authenticate {  
  104.     return YES;  
  105. }  
  106.   
  107. -(void) disConnect {  
  108.     XMPPPresence *presence = [XMPPPresence presenceWithType:@"unavailable"];  
  109.     [[self xmppStream] sendElement:presence];  
  110.     [xmppStream disconnect];  
  111. }  
  112.   
  113. #pragma mark XMPPStream Delegate  
  114.   
  115. - (void)xmppStreamWillConnect:(XMPPStream *)sender {  
  116.     DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);  
  117. }  
  118.   
  119. - (void)xmppStream:(XMPPStream *)sender socketDidConnect:(GCDAsyncSocket *)socket  {  
  120.     DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);  
  121. }  
  122.   
  123. - (void)xmppStreamDidConnect:(XMPPStream *)sender {  
  124.     DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);  
  125.     DDLogVerbose(@"jid is %@@%@, password is %@", xmppStream.myJID.user, xmppStream.myJID.domain, myPassword);  
  126.     NSError *error;  
  127.     if(![xmppStream authenticateWithPassword:myPassword error:&error]) {  
  128.         UIAlertView *alertViewFailedConn = [[UIAlertView alloc] initWithTitle:@"验证失败"   
  129.                                                                       message:@"详细请查看控制台"   
  130.                                                                      delegate:nil  
  131.                                                             cancelButtonTitle:@"OK"  
  132.                                                             otherButtonTitles:nil];  
  133.         [alertViewFailedConn show];  
  134.         [alertViewFailedConn release];  
  135.         DDLogError(@"Error authenticating: %@", error);  
  136.         return;  
  137.     }  
  138. }  
  139.   
  140. - (void)xmppStreamDidAuthenticate:(XMPPStream *)sender {  
  141.     DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);  
  142.     XMPPPresence *presence = [XMPPPresence presence];  
  143.     [xmppStream sendElement:presence];  
  144. }  
  145.   
  146. - (void)xmppStream:(XMPPStream *)sender didNotAuthenticate:(NSXMLElement *)error{  
  147.     DDLogVerbose(@"%@: %@", xmppStream.myJID.user, xmppStream.myJID.domain);  
  148. }  
  149.   
  150. - (void)xmppStream:(XMPPStream *)sender didReceiveError:(id)error  
  151. {  
  152.     DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);  
  153. }  
  154.   
  155. - (void)xmppStreamDidSecure:(XMPPStream *)sender {  
  156.     DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);  
  157. }  
  158.   
  159. - (void)xmppStream:(XMPPStream *)sender willSecureWithSettings:(NSMutableDictionary *)settings {  
  160.     DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);  
  161.     //[settings setObject:[NSNumber numberWithBool:YES] forKey:(NSString *)kCFStreamSSLAllowsAnyRoot];  
  162.     //[settings setObject:[NSNull null] forKey:(NSString *)kCFStreamSSLLevel];  
  163.     NSString *expectedCertName = nil;  
  164.       
  165.     NSString *serverDomain = xmppStream.hostName;  
  166.     NSString *virtualDomain = [xmppStream.myJID domain];  
  167.       
  168.     if ([serverDomain isEqualToString:@"talk.google.com"])  
  169.     {  
  170.         if ([virtualDomain isEqualToString:@"gmail.com"])  
  171.         {  
  172.             expectedCertName = virtualDomain;  
  173.         }  
  174.         else  
  175.         {  
  176.             expectedCertName = serverDomain;  
  177.         }  
  178.     }  
  179.     else if (serverDomain == nil)  
  180.     {  
  181.         expectedCertName = virtualDomain;  
  182.     }  
  183.     else  
  184.     {  
  185.         expectedCertName = serverDomain;  
  186.     }  
  187.       
  188.     if (expectedCertName)  
  189.     {  
  190.         [settings setObject:expectedCertName forKey:(NSString *)kCFStreamSSLPeerName];  
  191.     }  
  192. }  
  193.   
  194. - (void)xmppStream:(XMPPStream *)sender didReceiveMessage:(XMPPMessage *)message {  
  195.       
  196. }  
  197.   
  198. - (void)xmppStreamDidDisconnect:(XMPPStream *)sender withError:(NSError *)error {  
  199.     DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);  
  200.       
  201.     //if (!isXmppConnected) {  
  202. //      DDLogError(@"Unable to connect to server. Check xmppStream.hostName");  
  203. //  }  
  204. }  
  205.   
  206. - (void)xmppStream:(XMPPStream *)sender didReceivePresence:(XMPPPresence *)presence {  
  207.     DDLogVerbose(@"%@: %@ - %@", THIS_FILE, THIS_METHOD, [presence fromStr]);  
  208. }  
  209.   
  210. - (void)xmppRoster:(XMPPRoster *)sender didReceiveBuddyRequest:(XMPPPresence *)presence {  
  211.       
  212. }  
  213.   
  214. - (void)applicationWillResignActive:(UIApplication *)application {  
  215.     /* 
  216.      Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. 
  217.      Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. 
  218.      */  
  219. }  
  220.   
  221.   
  222. - (void)applicationDidEnterBackground:(UIApplication *)application {  
  223.     /* 
  224.      Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.  
  225.      If your application supports background execution, called instead of applicationWillTerminate: when the user quits. 
  226.      */  
  227.     DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);  
  228.       
  229. }  
  230.   
  231.   
  232. - (void)applicationWillEnterForeground:(UIApplication *)application {  
  233.     DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);  
  234. }  
  235.   
  236.   
  237. - (void)applicationDidBecomeActive:(UIApplication *)application {  
  238.     /* 
  239.      Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. 
  240.      */  
  241. }  
  242.   
  243.   
  244. - (void)applicationWillTerminate:(UIApplication *)application {  
  245.     /* 
  246.      Called when the application is about to terminate. 
  247.      See also applicationDidEnterBackground:. 
  248.      */  
  249. }  
  250.   
  251.   
  252. #pragma mark -  
  253. #pragma mark Memory management  
  254.   
  255. - (void)applicationDidReceiveMemoryWarning:(UIApplication *)application {  
  256.     /* 
  257.      Free up as much memory as possible by purging cached data objects that can be recreated (or reloaded from disk) later. 
  258.      */  
  259. }  
  260.   
  261.   
  262. - (void)dealloc {  
  263.     [self teardownStream];  
  264.     [xmppStream release];  
  265.     [xmppReconnect release];  
  266.     [myPassword release];  
  267.       
  268.     [viewController release];  
  269.     [window release];  
  270.     [super dealloc];  
  271. }  
  272.   
  273.   
  274. @end  


[cpp]  view plain copy
  1. //  
  2. //  XmppTest1ViewController.h  
  3. //  XmppTest1  
  4. //  
  5. //  Created by liu lavy on 11-10-2.  
  6. //  Copyright 2011 __MyCompanyName__. All rights reserved.  
  7. //  
  8.   
  9. #import <UIKit/UIKit.h>  
  10.   
  11. @interface XmppTest1ViewController : UIViewController {  
  12.     UITextField *fieldJid;  
  13.     UITextField *fieldPwd;  
  14. }  
  15.   
  16. @property (nonatomic, retain) IBOutlet UITextField *fieldJid;  
  17. @property (nonatomic, retain) IBOutlet UITextField *fieldPwd;  
  18.   
  19. -(IBAction) login:(id)sender;  
  20. -(IBAction) textFieldDownEditing:(id)sender;  
  21. -(IBAction) backgroundTap:(id)sender;  
  22. @end  


[cpp]  view plain copy
  1. //  
  2. //  XmppTest1ViewController.m  
  3. //  XmppTest1  
  4. //  
  5. //  Created by liu lavy on 11-10-2.  
  6. //  Copyright 2011 __MyCompanyName__. All rights reserved.  
  7. //  
  8.   
  9. #import "XmppTest1ViewController.h"  
  10. #import "XMPPFramework.h"  
  11. #import "DDLog.h"  
  12. #import "XmppTest1AppDelegate.h"  
  13.   
  14. #if DEBUG  
  15. static const int ddLogLevel = LOG_LEVEL_VERBOSE;  
  16. #else  
  17. static const int ddLogLevel = LOG_LEVEL_INFO;  
  18. #endif  
  19.   
  20.   
  21. @implementation XmppTest1ViewController  
  22. @synthesize fieldJid;  
  23. @synthesize fieldPwd;  
  24. -(XmppTest1AppDelegate *) appDelegate {  
  25.     return (XmppTest1AppDelegate *)[[UIApplication sharedApplication] delegate];  
  26. }  
  27.   
  28. -(IBAction) login:(id)sender {  
  29.     NSString *myJID = fieldJid.text;  
  30.     NSString *password = fieldPwd.text;  
  31.     if([[self appDelegate] connect:myJID password:password]) {  
  32.           
  33.     }  
  34. }  
  35.   
  36. -(IBAction) textFieldDownEditing:(id)sender {  
  37.     [sender resignFirstResponder];  
  38. }  
  39.   
  40. -(IBAction) backgroundTap:(id)sender {  
  41.     [fieldJid resignFirstResponder];  
  42.     [fieldPwd resignFirstResponder];  
  43. }  
  44.   
  45. /* 
  46. // The designated initializer. Override to perform setup that is required before the view is loaded. 
  47. - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { 
  48.     self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; 
  49.     if (self) { 
  50.         // Custom initialization 
  51.     } 
  52.     return self; 
  53. } 
  54. */  
  55.   
  56. /* 
  57. // Implement loadView to create a view hierarchy programmatically, without using a nib. 
  58. - (void)loadView { 
  59. } 
  60. */  
  61.   
  62.   
  63.   
  64. // Implement viewDidLoad to do additional setup after loading the view, typically from a nib.  
  65. - (void)viewDidLoad {  
  66.           
  67. }  
  68.   
  69.   
  70.   
  71. /* 
  72. // Override to allow orientations other than the default portrait orientation. 
  73. - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { 
  74.     // Return YES for supported orientations 
  75.     return (interfaceOrientation == UIInterfaceOrientationPortrait); 
  76. } 
  77. */  
  78.   
  79. - (void)didReceiveMemoryWarning {  
  80.     // Releases the view if it doesn't have a superview.  
  81.     [super didReceiveMemoryWarning];  
  82.       
  83.     // Release any cached data, images, etc that aren't in use.  
  84. }  
  85.   
  86. - (void)viewDidUnload {  
  87.     fieldJid = nil;  
  88.     fieldPwd = nil;  
  89.       
  90. }  
  91.   
  92.   
  93. - (void)dealloc {  
  94.     [fieldJid release];  
  95.     [fieldPwd release];  
  96.     [super dealloc];  
  97. }  
  98.   
  99. @end  

当然我也是看XMPPFramework里面的例子学习的,那是个好东西,下一步该学习怎样通过服务器发送消息了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值