上一篇講了XMPP的服務器和數據的配置,現在說一下代碼。在寫代碼之前我們需要打開我們配置好的服務器,至于怎么打開可以看上一篇文章。
1、使用cocoapods導入pod 'XMPPFramework'
2、新建一個PCH文件,導入一些頭文件,可以直接copy下面的。(如何配置pch文件路徑不懂得可以問我)
#import <Availability.h>
#ifndef __IPHONE_3_0
#warning "This project uses features only available in iOS SDK 3.0 and later."
#endif
#ifdef __OBJC__
#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>
#import <AVFoundation/AVFoundation.h>
#import <AFNetworking/AFNetworking.h>
#import <XMPP.h>
#define HTTPSERVER @"你的服務器域名,也就是.local結尾的"
#define MY_DOMAIN @"127.0.0.1"
#endif
3、到AppDelegate里面注冊XMPP
.h文件
//導入需要用到的頭文件
#import <XMPPRoster.h>
#import <XMPPMessageArchivingCoreDataStorage.h>
#import <XMPPReconnect.h>
#import <XMPPMessageArchiving.h>
#import <XMPPRosterCoreDataStorage.h>
//設置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 <XMPPUserCoreDataStorageObject.h>
#import <XMPPRosterCoreDataStorage.h>
#import <XMPPRoster.h>
@interface FriendTableViewController()<XMPPStreamDelegate,NSFetchedResultsControllerDelegate,XMPPRosterDelegate>
//確認代理獲取好友數據
-(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<NSFetchedResultsSectionInfo>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<NSFetchedResultsSectionInfo>)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進入聊天界面的代碼就不寫了,實在太多了,因為都是自定義的。
這種即時通訊比較復雜,用的比較多的還是第三方寫好的。不用自己搭服務器,聊天界面也是寫好的。比如融云,環信等等。
如果有什么問題大家可以一起解決!