ios xmpp研究探索:获取好友列表

/*
 一个 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];
    }
  }
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值