xmpp-iOS-获取好友列表、聊天信息列表、聊天

typedef enum {//发送消息类型的枚举

text,

image,

audio

} MsgType;

#import "XMPPData.h"
#import "XMPPFramework.h"

@interface XMPPData()<XMPPStreamDelegate,XMPPRosterDelegate,NSFetchedResultsControllerDelegate>
@property(strong,nonatomic) XMPPStream *xmppStream;
@property(assign,nonatomic) BOOL isRegister;
@property(strong,nonatomic) NSString*user,*pwd,*hostName,*domain;
@property(assign,nonatomic) UInt16 port;
@property(strong,nonatomic) XMPPRosterCoreDataStorage * rosterStorage;//花名册存储
@property(strong,nonatomic) XMPPRoster * rosterModule;//花名册模块
@property(strong,nonatomic) XMPPMessageArchivingCoreDataStorage *msgStorage;//消息存储
@property(strong,nonatomic) XMPPMessageArchiving * msgModule;//消息模块
@property(strong,nonatomic) NSFetchedResultsController *fetFriend;//查询好友的Fetch
@property(strong,nonatomic) NSFetchedResultsController *fetMsgRecord;//查询消息的Fetch
@end

@implementation XMPPData

//开始连接聊天服务器
-(BOOL) connectWithUserName:(NSString*) username andPwd:(NSString*) pwd andHostName:(NSString*) hostname andDomain:(NSString*) domain andHostPort:(UInt16) port andIsRegister:(BOOL) isRegister
{
    self.hostName = hostname;
    self.port = port;
    self.domain = domain;
    self.user = username;
    self.pwd = pwd;
    self.isRegister = isRegister;
    self.xmppStream = [[XMPPStream alloc] init];
    //设置代理
    [self.xmppStream addDelegate:self delegateQueue:dispatch_get_global_queue(0, 0)];
    //设置聊天服务器地址
    self.xmppStream .hostName = hostname;
    //设置聊天服务器端口 默认是5222
    self.xmppStream.hostPort = port;
    //设置Jid 就是用户名
    XMPPJID *jid = [XMPPJID jidWithUser:username domain:domain resource:@"test"];
    self.xmppStream.myJID = jid;
    NSError * error = nil;
    //验证连接
    [self.xmppStream connectWithTimeout:XMPPStreamTimeoutNone error:&error];
    if (error) {
        NSLog(@"连接失败:%@",error);
        return NO;
    }
    else
    {
        //注册所有的模块
        [self activeModules];
        return  YES;
    }
}

//激活相关的模块
-(void) activeModules
{
    //1.花名册存储对象
    self.rosterStorage = [XMPPRosterCoreDataStorage sharedInstance];
    //2.花名册模块
    self.rosterModule = [[XMPPRoster alloc] initWithRosterStorage:self.rosterStorage];
    //3.激活此模块
    [self.rosterModule activate:self.xmppStream];
    //4.添加roster代理
    [self.rosterModule addDelegate:self delegateQueue:dispatch_get_main_queue()];

    //1.消息存储对象
    self.msgStorage = [XMPPMessageArchivingCoreDataStorage sharedInstance];
    self.msgModule = [[XMPPMessageArchiving alloc] initWithMessageArchivingStorage:self.msgStorage];
    [self.msgModule activate:self.xmppStream];
    [self.msgModule addDelegate:self delegateQueue:dispatch_get_main_queue()];

}

//下线
-(void) logout
{
    //1.用户下线
    NSLog(@"注销用户");
    XMPPPresence *presene=[XMPPPresence presenceWithType:@"unavailable"];
    //设置下线状态
    [_xmppStream sendElement:presene];
    //2.断开连接
    [_xmppStream disconnect];

}

//添加好友
-(BOOL) addFriend:(NSString*) friendName
{
    XMPPJID * friendJid = [XMPPJID jidWithString:[NSString stringWithFormat:@"%@@%@",friendName,self.domain]];
    [self.rosterModule subscribePresenceToUser:friendJid];
    return YES;
}

//删除好友
-(BOOL) deleteFriend:(NSString*) friendName
{
    XMPPJID * friendJid = [XMPPJID jidWithString:[NSString stringWithFormat:@"%@@%@",friendName,self.domain]];
    [self.rosterModule removeUser:friendJid];
    return  YES;

}

//获取好友列表
-(NSArray*) getFriends
{
    NSManagedObjectContext *context = self.rosterStorage.mainThreadManagedObjectContext;
    NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"XMPPUserCoreDataStorageObject"];

    //筛选本用户的好友
    NSString *userinfo = [NSString stringWithFormat:@"%@@%@",self.user,self.domain];

    NSLog(@"userinfo = %@",userinfo);
    NSPredicate *predicate =
    [NSPredicate predicateWithFormat:@" streamBareJidStr = %@ ",userinfo];
    request.predicate = predicate;

    //排序
    NSSortDescriptor * sort = [NSSortDescriptor sortDescriptorWithKey:@"displayName" ascending:YES];
    request.sortDescriptors = @[sort];

    self.fetFriend = [[NSFetchedResultsController alloc] initWithFetchRequest:request managedObjectContext:context sectionNameKeyPath:nil cacheName:nil];
    self.fetFriend.delegate = self;
    NSError *error;
    [self.fetFriend performFetch:&error];

    //返回的数组是XMPPUserCoreDataStorageObject  *obj类型的
    //名称为 obj.displayName
    NSLog(@"%lu",(unsigned long)self.fetFriend.fetchedObjects.count);
    return  self.fetFriend.fetchedObjects;
}

//数据库有变化
-(void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type newIndexPath:(NSIndexPath *)newIndexPath
{
    NSManagedObject *obj = anObject;
    if([obj isKindOfClass:[XMPPMessageArchiving_Message_CoreDataObject class]])
    {
         NSLog(@"<span style="font-family: Arial, Helvetica, sans-serif;">聊天的信息的数据库发生变化</span>");
    }
    else
        NSLog(@"数据库有变化");
}

//与某个好友聊天
-(BOOL) talkToFriend:(NSString*)friendsName andMsg:(NSString*) msg  andMsgType:(MsgType) msgT
{
    XMPPJID *toFriend = [XMPPJID jidWithUser:friendsName domain:self.domain resource:@"A"];//resource 随意,目前不影响
    XMPPMessage * message = [[XMPPMessage alloc] initWithType:@"chat" to:toFriend];//chat类型是正常的聊天类型
    [message addBody:msg];
    [message addAttributeWithName:@"msgType" intValue:msgT];
    [self.xmppStream sendElement:message];
    return YES;
}

//获得与某个好友的聊天记录
-(NSArray*) getRecords:(NSString*) friendsName
{

    //所有账号 和所有人的聊天记录都在同一个数据库内  所以 要写查询条件
    NSManagedObjectContext *context = self.msgStorage.mainThreadManagedObjectContext;
    NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"XMPPMessageArchiving_Message_CoreDataObject"];
    NSString *userinfo = [NSString stringWithFormat:@"%@@%@",self.user,self.domain];
    NSString *friendinfo = [NSString stringWithFormat:@"%@@%@",friendsName,self.domain];
    NSPredicate *predicate =
    [NSPredicate predicateWithFormat:@" streamBareJidStr = %@ and bareJidStr = %@",userinfo,friendinfo];
    request.predicate = predicate;

    NSSortDescriptor * sort = [NSSortDescriptor sortDescriptorWithKey:@"timestamp" ascending:YES];
    request.sortDescriptors = @[sort];
    self.fetMsgRecord = [[NSFetchedResultsController alloc] initWithFetchRequest:request managedObjectContext:context sectionNameKeyPath:nil cacheName:nil];
    self.fetMsgRecord.delegate = self;
    NSError *error;
    [self.fetMsgRecord performFetch:&error];
//   返回的值类型 XMPPMessageArchiving_Message_CoreDataObject
    return self.fetMsgRecord.fetchedObjects;
}

//连接成功的代理函数
-(void)xmppStreamDidConnect:(XMPPStream *)sender
{
    NSLog(@"连接成功");
    if (self.isRegister) {
        NSError* error = nil;
        [sender registerWithPassword:self.pwd error:&error];
        if (error) {
            NSLog(@"注册失败1,%@",error);
        }
    }
    else
    {
        NSError *error = nil;
        [sender authenticateWithPassword:self.pwd error:&error];
        if (error) {
            NSLog(@"验证失败1,%@",error);
        }
    }
}
//连接失败代理函数
-(void)xmppStreamDidDisconnect:(XMPPStream *)sender withError:(NSError *)error
{
    NSLog(@"连接失败,%@",error);
}

//验证成功代理函数
-(void)xmppStreamDidAuthenticate:(XMPPStream *)sender
{
    NSLog(@"验证成功");
    //4.登陆成功后 在线
    [self.xmppStream sendElement:[XMPPPresence presence]];//用户在线
}
//验证失败代理函数
-(void)xmppStream:(XMPPStream *)sender didNotAuthenticate:(DDXMLElement *)error
{
    NSLog(@"验证失败,%@",error);
}

//注册成功代理函数
-(void)xmppStreamDidRegister:(XMPPStream *)sender
{
    NSLog(@"注册成功");
}

//注册失败代理函数
-(void)xmppStream:(XMPPStream *)sender didNotRegister:(DDXMLElement *)error
{
    NSLog(@"注册失败,%@",error);
}

//收到好友请求 代理函数
-(void)xmppRoster:(XMPPRoster *)sender didReceivePresenceSubscriptionRequest:(XMPPPresence *)presence
{
    NSString * presenceType = [presence type];
    NSLog(@"presenceType = %@",presenceType);
    XMPPJID * fromJid = presence.from;
    if ([presenceType isEqualToString:@"subscribe"]) {//是订阅请求  直接通过
        [self.rosterModule acceptPresenceSubscriptionRequestFrom:fromJid andAddToRoster:YES];
    }
}

-(void)xmppRoster:(XMPPRoster *)sender didReceiveRosterItem:(DDXMLElement *)item
{
    NSString *subscription = [item attributeStringValueForName:@"subscription"];
    NSLog(@"%@",subscription);
    if ([subscription isEqualToString:@"both"]) {
        NSLog(@"双方成为好友!");
    }
}

@end

demo下载地址:

以上就是代码的主要内容

时间: 2024-10-16 03:00:53

xmpp-iOS-获取好友列表、聊天信息列表、聊天的相关文章

iOS获取类的属性列表

通过实例讲解: @interface DemoObject : NSObject @property (strong, nonatomic,readonly) NSString *name; @property (strong, nonatomic) NSMutableArray *dataSource; @property (copy, nonatomic) NSDictionary *product; @property (assign, atomic) NSUInteger count;

一步一步来做WebQQ机器人-(四)(获取好友列表和群列表)

× 本篇主要是: 获取好友列表,群列表 我会尽量详细一点,尽我所知的分享一些可能大家已经掌握的或者还不清楚的经验 利于大家阅读,文章样式不再复杂化,根据内容取固定色 目前总进度大概65% 全系列预计会有这些步骤,当然某些步骤可能会合并: 验证码 第一次登陆 第二次登陆 保持在线和接收消息 获取好友和群列表 发送消息 变成智能的(*?∀?*) 获取好友 1-获取QQ好友的hash算法 P = function (b, j) { for (var a = j + "password error&qu

UI进阶 即时通讯之XMPP好友列表、添加好友、获取会话内容、简单聊天

这篇博客的代码是直接在上篇博客的基础上增加的,先给出部分代码,最后会给出能实现简单功能的完整代码. UI进阶 即时通讯之XMPP登录.注册 1.好友列表 初始化好友花名册 1 #pragma mark - 管理好友 2 // 获取管理好友的单例对象 3 XMPPRosterCoreDataStorage *rosterStorage = [XMPPRosterCoreDataStorage sharedInstance]; 4 // 用管理好友的单例对象初始化Roster花名册 5 // 好友操

即时通讯之XMPP好友列表、添加好友、获取会话内容、简单聊天

1.好友列表 初始化好友花名册 1 #pragma mark - 管理好友 2 // 获取管理好友的单例对象 3 XMPPRosterCoreDataStorage *rosterStorage = [XMPPRosterCoreDataStorage sharedInstance]; 4 // 用管理好友的单例对象初始化Roster花名册 5 // 好友操作是耗时操作 6 self.xmppRoster = [[XMPPRoster alloc] initWithRosterStorage:r

XMPP系列(三)---获取好友列表、添加好友

1.心跳检测.掉线重连功能 客户端和服务器端都可以设置多久发送一次心跳包,如果对方没有返回正确的pong信息,则会断开连接,而添加掉线重连功能,则会自动进行连接. 如果自己写聊天功能还得自己做心跳检测和掉线重连,比较麻烦.好在XMPP中已经做了心跳检测和掉线重连的模块,只需要几行代码加进去就能实现掉线重连,非常方便. XMPP中Extensions文件下都是可以自己添加的Module,它们都继承自XMPPModule,而添加的方法也非常的简单: <span style="font-size

XMPP开发之获取好友列表

前面在<XMPP开发之adium客户端登陆>中和大家分享了登录的代码和常遇到的问题.几天和大家分享获取好友列表以及相关的问题. 说到获取好友列表,那么很有必要说一下首先网站上gitHub上给出的demo其实是有点问题的,主要就是coredata的文件,有问题,刚开始一直报错,存取都失败,后来发现了我按照他们原来的字段重新建了一个coredata的文件,另外由于这里只是一个demo所以知识简单的实现了好友从a~z的排序,还有就是分组还没有实现,这个等以后把这一块完善后和大家分享下. 如果要有好友

xmpp开发教程(四)-获取好友列表

这章节主要是介绍如何获取好友列表,在这里主要是做功能部分,后续更新的时候就将界面也做上去 首先提供下核心代码 1 xmppRosterStorage = [[XMPPRosterCoreDataStorage alloc] init]; 2 // xmppRosterStorage = [[XMPPRosterCoreDataStorage alloc] initWithInMemoryStore]; 3 4 xmppRoster = [[XMPPRoster alloc] initWithRo

iOS 获取 WiFi 列表

IOS 获取 WIFi列表有2016 /11 / 10 之后就不用申请权限了  Apple 官方邮件回复: Thank you for requesting information about the Network Extension framework. Please note that as of November 10, 2016 this process is not required for developers who wish to use App Proxy, Content

xmpp获取好友信息和添加删除好友(4)

原始地址: XMPPFrameWork IOS 开发(五)获取好友信息和添加删除好友 好友列表和好友名片 [cpp] view plaincopyprint? [_xmppRoster fetchRoster];//获取好友列表 //获取到一个好友节点 - (void)xmppRoster:(XMPPRoster *)sender didRecieveRosterItem:(NSXMLElement *)item //获取完好友列表 - (void)xmppRosterDidEndPopulat