/*
一个 IQ 请求:
<iq type="get"
from="xiaoming@example.com"
to="example.com"
id="1234567">
<query xmlns="jabber:iq:roster"/>
<iq />
type 属性,说明了该 iq 的类型为 get,与 HTTP 类似,向服务器端请求信息
from 属性,消息来源,这里是你的 JID
to 属性,消息目标,这里是服务器域名
id 属性,标记该请求 ID,当服务器处理完毕请求 get 类型的 iq 后,响应的 result 类型 iq 的 ID 与 请求 iq 的 ID 相同
<query xmlns="jabber:iq:roster"/> 子标签,说明了客户端需要查询 roster
*/
- (void)fetchBuddyListWithCompletion:(HYBFetchResultBlock)completion {
self.buddyListBlock = completion;
// 通过coredata获取好友列表
NSManagedObjectContext *context = [self rosterContext];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"XMPPUserCoreDataStorageObject"
inManagedObjectContext:context];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:entity];
__block NSError *error = nil;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSArray *results =[context executeFetchRequest:request error:&error];
dispatch_async(dispatch_get_main_queue(), ^{
if (completion) {
completion(results, [error description]);
}
});
});
// 下面的方法是从服务器中查询获取好友列表
// // 创建iq节点
// NSXMLElement *iq = [NSXMLElement elementWithName:@"iq"];
// [iq addAttributeWithName:@"type" stringValue:@"get"];
// [iq addAttributeWithName:@"from" stringValue:[NSString stringWithFormat:@"%@@%@", _jid, kServer]];
// [iq addAttributeWithName:@"to" stringValue:kServer];
// [iq addAttributeWithName:@"id" stringValue:kFetchBuddyListQueryID];
// // 添加查询类型
// NSXMLElement *query = [NSXMLElement elementWithName:@"query" xmlns:@"jabber:iq:roster"];
// [iq addChild:query];
//
// // 发送查询
// [_xmppStream sendElement:iq];
}
另外,在对方同意添加为好友时,也更新好友列表:
/**
* Sent when the roster receives a roster item.
*
* Example:
*
* <item jid='romeo@example.net' name='Romeo' subscription='both'>
* <group>Friends</group>
* </item>
**/
// 已经互为好友以后,会回调此
- (void)xmppRoster:(XMPPRoster *)sender didReceiveRosterItem:(NSXMLElement *)item {
NSString *subscription = [item attributeStringValueForName:@"subscription"];
if ([subscription isEqualToString:@"both"]) {
NSLog(@"双方已经互为好友");
if (self.buddyListBlock) {
// 更新好友列表
[self fetchBuddyListWithCompletion:self.buddyListBlock];
}
}
}