XMPP For iPhone 学习笔记<二>

新建一个 MyXMPP 的操作类

并作为一个属性在 AppDelegate 中添加并init

@property (strong, nonatomic) MyXMPP *myXMPP;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    [self.window makeKeyAndVisible];
    LoginViewController *loginViewController = [[LoginViewController alloc] initWithNibName:nil bundle:nil];
    self.window.rootViewController = loginViewController;
    self.myXMPP = [[MyXMPP alloc] init];
    
    return YES;
}


在 MyXMPP 中创建一个连接方法

- (BOOL)connect:(NSString *)account password:(NSString *)password host:(NSString *)host success:(CallBackBlock)Success fail:(CallBackBlockErr)Fail;

- (BOOL)connect:(NSString *)account password:(NSString *)password host:(NSString *)host success:(CallBackBlock)Success fail:(CallBackBlockErr)Fail
{
    if (self.xmppStream == nil) {
        self.xmppStream = [[XMPPStream alloc] init];
        [self.xmppStream addDelegate:self delegateQueue:dispatch_get_main_queue()];
    }

    self.password = password;
    self.success = Success;
    
    self.fail = Fail;
    if (![self.xmppStream isDisconnected]) {
        return YES;
    }
    
    if (account == nil) {
        return NO;
    }
    
    [self.xmppStream setMyJID:[XMPPJID jidWithString:account]];
    [self.xmppStream setHostName:host];
    
    NSError *err = nil;
    if (![self.xmppStream connectWithTimeout:30 error:&err]) {
        NSLog(@"cant connect %@", host);
        Fail(err);
        return NO;
    }
    
    return YES;
}

该方法成功后会回调

// connect 成功后回调
- (void)xmppStreamDidConnect:(XMPPStream *)sender {
    NSLog(@"connected");
    NSError *error = nil;
    
    [[self xmppStream] authenticateWithPassword:self.password error:&error];
    if(error!=nil)
    {
        NSLog(@"login fail");
        self.fail(error);
    }
}

并在其中调用 authenticateWithPassword 方法进行验证登陆

authenticateWithPassword 成功后会回调

- (void)xmppStreamDidAuthenticate:(XMPPStream *)sender {
    [self goOnline];
    self.success();
}

authenticateWithPassword 失败后会回调

// authenticateWithPassword 失败后调用
- (void)xmppStream:(XMPPStream *)sender didNotAuthenticate:(NSXMLElement *)error {
    NSLog(@"not authenticated");
    NSError *err = [[NSError alloc] initWithDomain:Domain code:-100 userInfo:@{@"detail": @"not authorized"}];
    self.fail(err);
}


验证登陆成功后调用 goOnline ,上线的方法

- (void)goOnline {
    XMPPPresence *presence = [XMPPPresence presence];
    [[self xmppStream] sendElement:presence];
}


同步代码地址:https://github.com/dapang/XMPP_For_iPhone


你可能感兴趣的:(ios,Objective-C,XMPP)