这里记录下我实现添加好友的过程,网上虽然也有相应的例子,但说的不是很全面,其中有一篇没有给出
XMPPRoster类的初始化。我找这个类的初始化设置找了好久。不多说啦。下面开始贴代码啦。
初始化XMPPRoster 对象声明
@interface XMPPModel()<XMPPStreamDelegate,XMPPRosterDelegate> @property (nonatomic , strong) XMPPStream *xmppStream; @property (nonatomic , strong) XMPPRoster *xmppRoster; //用户对象 @property (nonatomic , strong) XMPPRosterCoreDataStorage *xmppRosterDataStorage; @end
实现1 这里只是先初始化_xmppRoster 这个对象,
// 初始化方法 - (void)setupStream { _xmppStream = [[XMPPStream alloc] init]; [_xmppStream addDelegate:self delegateQueue:dispatch_get_main_queue()]; _xmppRosterDataStorage = [[XMPPRosterCoreDataStorage alloc] init]; _xmppRoster = [[XMPPRoster alloc] initWithRosterStorage:_xmppRosterDataStorage]; // _xmppRoster.autoFetchRoster = YES; // _xmppRoster.autoAcceptKnownPresenceSubscriptionRequests = YES; // }
实现2 下面是登陆成功的回调,在下面的回调中添加下面代码:
// 登陆成功 - (void) xmppStreamDidAuthenticate:(XMPPStream *)sender { [self goOnline]; NSLog(@"登陆成功"); [[NSUserDefaults standardUserDefaults] setObject:@"success" forKey:XMPPLogin]; [_xmppRoster activate:_xmppStream]; [_xmppRoster addDelegate:self delegateQueue:dispatch_get_main_queue()]; }
上面的代码作用是将_xmppRoster对象与_xmppStream联系在一起。这样就能实现添加好友了,注意
[_xmppRosteractivate:_xmppStream];
这行代码要写在登陆成功回调的方法里,如果写在初始化
- (void)setupStream 这个方法里会出现死循环。
下面在贴下添加好友和处理好友请求的方法,下面的代码百度上又很多,主要的是上面的代码。
// // XMPPModel+Friend.m // XMPPTest // // Created by qitmac000246 on 12/26/14. // Copyright (c) 2014 杜甲. All rights reserved. // #import "XMPPModel+Friend.h" @implementation XMPPModel (Friend) // 添加好友 - (void)addFriend:(NSString *)jidString xmppRoster:(XMPPRoster *)xmppRoster { XMPPJID *jid = [XMPPJID jidWithString:[NSString stringWithFormat:@"%@@%@",jidString,@"shenqi"]]; [xmppRoster subscribePresenceToUser:jid]; } //接受好友请求 - (void) receiveContact:(XMPPStream *)sender presence:(XMPPPresence *)presence xmppRoster:(XMPPRoster *)xmppRoster { NSString *presenceType = presence.type; NSString *userId = sender.myJID.user; NSString *presenceFromUser = presence.from.user; if (![presenceFromUser isEqualToString:userId]) { // 用户在线 if ([presenceType isEqualToString:@"available"]) { }else if([presenceType isEqualToString:@"unavailable"]) { }else if ([presenceType isEqualToString:@"subscribe"]) { // NSLog(@"%@",presence.description); // NSLog(@"%@",presence.from); XMPPJID *jid = [XMPPJID jidWithString:[NSString stringWithFormat:@"%@",presence.from]]; [xmppRoster acceptPresenceSubscriptionRequestFrom:jid andAddToRoster:YES]; } } } @end
原文地址:http://write.blog.csdn.net/postedit/42271089
时间: 2024-10-23 00:15:44