上一篇讲了XMPP的服务器和数据的配置,现在说一下代码。在写代码之前我们需要打开我们配置好的服务器,至于怎么打开可以看上一篇文章。
1、使用cocoapods导入pod 'XMPPFramework'
2、新建一个PCH文件,导入一些头文件,可以直接copy下面的。(如何配置pch文件路径不懂得可以问我)
#import
#ifndef __IPHONE_3_0
#warning "This project uses features only available in iOS SDK 3.0 and later."
#endif
#ifdef __OBJC__
#import
#import
#import
#import
#import
#import
#define HTTPSERVER @"你的服务器域名,也就是.local结尾的"
#define MY_DOMAIN @"127.0.0.1"
#endif
3、到AppDelegate里面注册XMPP
.h文件
//导入需要用到的头文件
#import
#import
#import
#import
#import
//设置XMPP流属性和coredata属性
@property(nonatomic,strong)XMPPStream*xmppStream;
@property(strong,nonatomic)NSManagedObjectContext*xmppManagedObjectContext;
@property(strong,nonatomic)NSManagedObjectContext*xmppRosterManagedObjectContext;
.m文件
//设置全局变量
XMPPReconnect*xmppReconnect;//重新连接
XMPPMessageArchiving* xmppMessageArchiving;//消息保存
//把请求的数据添加到CoreDate中
XMPPMessageArchivingCoreDataStorage* messageStorage;
XMPPRoster*xmppRoster;
//好友列表保存
XMPPRosterCoreDataStorage*xmppRosterStorage;
- (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions {
// Override point for customization after application launch.
[self xmppInit];
return YES;
}
//初始化XMPP
-(void)xmppInit{
self.xmppStream= [[XMPPStream alloc] init];//创建xmppstream
xmppReconnect= [[XMPPReconnect alloc] init];//创建重写连接组件
[xmppReconnect activate:self.xmppStream];//使组件生效
//创建消息保存策略(规则,规定)
messageStorage= [XMPPMessage ArchivingCoreDataStorage sharedInstance];
//用消息保存策略创建消息保存组件
xmppMessageArchiving= [[XMPPMessage Archiving alloc]initWithMessageArchivingStorage:messageStorage];
//使组件生效
[xmppMessageArchiving activate:self.xmppStream];
//提取消息保存组件的coreData上下文
self.xmppManagedObjectContext=messageStorage.mainThreadManagedObjectContext;
xmppRosterStorage= [[XMPPRosterCoreDataStorage alloc]init];
xmppRoster= [[XMPPRoster alloc]initWithRosterStorage:xmppRosterStorage];
//自动获取用户列表
xmppRoster.autoFetchRoster=YES;
xmppRoster.autoAcceptKnownPresenceSubscriptionRequests=YES;
[xmppRoster activate:self.xmppStream];
self.xmppRosterManagedObjectContext=xmppRosterStorage.mainThreadManagedObjectContext;
}
4、布局登陆UI,这里就不给出代码了。
5、再登陆的控制器里面,添加代理XMPPStreamDelegate,然后初始化XMPP
//初始化XMPP
-(void)initXMPP{
UIApplication*application = [UIApplicationsharedApplication];
iddelegate = [applicationdelegate];
self.xmppStream= [delegatexmppStream];
[self.xmppStreamaddDelegate:selfdelegateQueue:dispatch_get_main_queue()];
}
6、验证登陆信息
//验证账号和密码
-(void)xmppConnect{
if(![_loginView.nameTF.text isEqualToString:@""] && ![_loginView.pwdTF.text isEqualToString:@""]) {
XMPPJID*jid = [XMPPJID jidWithUser:_loginView.nameTF.text domain:MY_DOMAINresource:@"iPhone"];
[self.xmppStreamsetMyJID:jid];
NSError*error =nil;
[self.xmppStream connectWithTimeout:4error:&error];
if(error) {
NSLog(@"链接出错:%@",[error localizedDescription]);
}
error =nil;
[self.xmppStream authenticateWithPassword:_loginView.pwdTF.texterror:&error];
if(error) {
NSLog(@"认证错误:%@",[error localizedDescription]);
}
}else{
NSLog(@"用户名、密码不能为空");
}
}
//验证成功后转跳到好友列表
-(void)xmppStreamDidAuthenticate:(XMPPStream*)sender{
NSLog(@"登录成功");
XMPPPresence*pre = [XMPPPresencepresence];
[self.xmppStreamsendElement:pre];
UIStoryboard*storyboard = [UIStoryboardstoryboardWithName:@"Main"bundle:nil];
FriendTableViewController*friendTVC = [storyboardinstantiateViewControllerWithIdentifier:@"FriendTableViewController"];
[self.navigationControllerpushViewController:friendTVCanimated:NO];
}
//登陆失败执行该方法
-(void)xmppStream:(XMPPStream*)sender didNotAuthenticate:(DDXMLElement*)error{
NSLog(@"认证失败");
}
7、好友列表的获取
//导入头文件,遵循代理
#import
#import
#import
@interface FriendTableViewController()
//确认代理获取好友数据
-(void)refrash{
UIApplication*application = [UIApplicationsharedApplication];
iddelegate = [applicationdelegate];
self.xmppRosterManagedObjectContext= [delegatexmppRosterManagedObjectContext];
NSFetchRequest*request = [[NSFetchRequestalloc]initWithEntityName:NSStringFromClass([XMPPUserCoreDataStorageObjectclass])];
NSSortDescriptor*sortD = [NSSortDescriptorsortDescriptorWithKey:@"jidStr"ascending:YES];
[requestsetSortDescriptors:@[sortD]];
//获取FRC
self.fetchedResultsController= [[NSFetchedResultsControlleralloc]initWithFetchRequest:requestmanagedObjectContext:self.xmppRosterManagedObjectContextsectionNameKeyPath:nilcacheName:nil];
self.fetchedResultsController.delegate=self;
NSError*error =nil;
if(![self.fetchedResultsControllerperformFetch:&error]) {
NSLog(@"%s%@",__FUNCTION__,[errorlocalizedDescription]);
}
[self.tableViewreloadData];
}
//获取组数
- (NSInteger)numberOfSectionsInTableView:(UITableView*)tableView {
NSArray*sections = [self.fetchedResultsControllersections];
returnsections.count;
}
//获取行数
- (NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section {
NSArray*sections = [self.fetchedResultsController sections];
id
sectionInfo = sections[section]; return[sectionInfonumberOfObjects];
}
//对cell进行赋值
- (UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath {
FriendTableViewCell*cell = [tableViewdequeueReusableCellWithIdentifier:CellIDforIndexPath:indexPath];
XMPPUserCoreDataStorageObject*roster = [self.fetchedResultsControllerobjectAtIndexPath:indexPath];
cell.nameLabel.text= roster.nickname;
cell.lineView.backgroundColor= [UIColor lightGrayColor];
return cell;
}
//实现NSFetchedResultsControllerDelegate代理方法
//对NSFetchedResultsController进行跟踪,实时改变UITableView,跟beginUpdates一起使用。
- (void)controllerWillChangeContent:(NSFetchedResultsController*)controller {
[self.tableViewbeginUpdates];
}
//通知代理的添加或者删除。当控制器改变sectionInfo时,fetchedObjects也会随之变化
- (void)controller:(NSFetchedResultsController*)controller didChangeSection:(id
)sectionInfo atIndex:(NSUInteger)sectionIndex forChangeType:(NSFetchedResultsChangeType)type {
switch(type) {
caseNSFetchedResultsChangeInsert:
[self.tableViewinsertSections:[NSIndexSetindexSetWithIndex:sectionIndex]
withRowAnimation:UITableViewRowAnimationFade];
break;
caseNSFetchedResultsChangeDelete:
[self.tableViewdeleteSections:[NSIndexSetindexSetWithIndex:sectionIndex]
withRowAnimation:UITableViewRowAnimationFade];
break;
}
}
//获取改变的对象,并对indexPath所对应的值进行修改。
- (void)controller:(NSFetchedResultsController*)controller didChangeObject:(id)anObject
atIndexPath:(NSIndexPath*)indexPath forChangeType:(NSFetchedResultsChangeType)type
newIndexPath:(NSIndexPath*)newIndexPath {
UITableView*tableView =self.tableView;
switch(type) {
caseNSFetchedResultsChangeInsert:
[tableViewinsertRowsAtIndexPaths:[NSArrayarrayWithObject:newIndexPath]
withRowAnimation:UITableViewRowAnimationFade];
break;
caseNSFetchedResultsChangeDelete:
[tableViewdeleteRowsAtIndexPaths:[NSArrayarrayWithObject:indexPath]
withRowAnimation:UITableViewRowAnimationFade];
break;
caseNSFetchedResultsChangeUpdate:
[tableViewreloadRowsAtIndexPaths:@[indexPath]withRowAnimation:UITableViewRowAnimationFade];
break;
caseNSFetchedResultsChangeMove:
[tableViewdeleteRowsAtIndexPaths:[NSArrayarrayWithObject:indexPath]
withRowAnimation:UITableViewRowAnimationFade];
[tableViewinsertRowsAtIndexPaths:[NSArrayarrayWithObject:newIndexPath]
withRowAnimation:UITableViewRowAnimationFade];
break;
}
}
//停止
- (void)controllerDidChangeContent:(NSFetchedResultsController*)controller {
[self.tableViewendUpdates];
}
好友获取基本就是这样了,接下来点击cell进入聊天界面的代码就不写了,实在太多了,因为都是自定义的。
这种即时通讯比较复杂,用的比较多的还是第三方写好的。不用自己搭服务器,聊天界面也是写好的。比如融云,环信等等。
如果有什么问题大家可以一起解决!