前一篇搭好了骨架,這次把功能補齊:登入、取得好友列表、聊天(文字、表情、圖片、語音)以及最近聯絡人。以下先講元件初始化,再逐段拆解核心程式碼。
登入的過程,本質上就是用 XMPPFramework 連上 Openfire 伺服器。若使用者曾登入過,就從 UserDefaults 取出 JID 與密碼自動連線;否則顯示登入畫面。好友列表則由 Roster 元件負責維護。
聊天訊息的傳輸策略:
之後任何地方要用 xmppStream,都透過 AppDelegate 取得。
self.xmppStream = [[XMPPStream alloc] init];
xmppReconnect = [[XMPPReconnect alloc] init]; [xmppReconnect activate:self.xmppStream];
收到的訊息要落地保存,顯示時再從資料庫讀取。初始化時必須指定保存策略(CoreData 或記憶體),實例化時關聯該策略,之後同樣要 activate,最後取出 CoreData 的 context:
messageStorage = [XMPPMessageArchivingCoreDataStorage sharedInstance]; xmppMessageArchiving = [[XMPPMessageArchiving alloc] initWithMessageArchivingStorage:messageStorage]; [xmppMessageArchiving activate:self.xmppStream]; 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;
可以注意到,XMPPFramework 的元件初始化步驟高度一致:建立 storage → 建立元件並注入 storage → 設定選項 → activate → 取 context。熟悉這個節奏之後,其他元件(vCard、OneToOneChat 等)都能快速上手。
-(void)initXmpp
{
UIApplication *application = [UIApplication sharedApplication];
id delegate = [application delegate];
self.xmppStream = [delegate xmppStream];
[self.xmppStream addDelegate:self delegateQueue:dispatch_get_main_queue()];
}
-(void)xmppConnect
{
if (![self.userNameTextFiled.text isEqualToString:@""] && self.userNameTextFiled.text != nil) {
// 建立 JID
XMPPJID *jid = [XMPPJID jidWithUser:self.userNameTextFiled.text
domain:MY_DOMAIN
resource:@"iPhone"];
[self.xmppStream setMyJID:jid];
NSError *error = nil;
[self.xmppStream connectWithTimeout:10 error:&error];
if (error) {
NSLog(@"連接出錯:%@", [error localizedDescription]);
}
} else {
UIAlertView *alter = [[UIAlertView alloc] initWithTitle:@"提示"
message:@"用戶名不能為空"
delegate:nil
cancelButtonTitle:@"取消"
otherButtonTitles:nil];
[alter show];
}
}
-(void)xmppStreamDidConnect:(XMPPStream *)sender
{
if (![self.passwordTextFiled.text isEqualToString:@""] && self.passwordTextFiled.text != nil) {
NSError *error = nil;
[self.xmppStream authenticateWithPassword:self.passwordTextFiled.text error:&error];
if (error) {
NSLog(@"認證錯誤:%@", [error localizedDescription]);
}
} else {
// 提示密碼不可為空
}
}
-(void)xmppStreamDidAuthenticate:(XMPPStream *)sender
{
NSLog(@"登陸成功");
// 保存帳密以便下次自動登入
NSUserDefaults *userDefult = [NSUserDefaults standardUserDefaults];
[userDefult setObject:self.userNameTextFiled.text forKey:@"username"];
[userDefult setObject:self.passwordTextFiled.text forKey:@"password"];
// 設定在線狀態
XMPPPresence *pre = [XMPPPresence presence];
[self.xmppStream sendElement:pre];
UIStoryboard *storybard = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
UIViewController *viewController = [storybard instantiateViewControllerWithIdentifier:@"mainController"];
[self presentViewController:viewController animated:YES completion:^{}];
}
// 認證失敗
-(void)xmppStream:(XMPPStream *)sender didNotAuthenticate:(DDXMLElement *)error
{
NSLog(@"認證失敗");
}
NSUserDefaults *userDefult = [NSUserDefaults standardUserDefaults];
NSString *userName = [userDefult objectForKey:@"username"];
NSString *password = [userDefult objectForKey:@"password"];
if (userName != nil && password != nil
&& ![userName isEqualToString:@""] && ![password isEqualToString:@""]) {
self.userNameTextFiled.text = userName;
self.passwordTextFiled.text = password;
[self xmppConnect];
}
因為 Roster 初始化時指定了 CoreData 作為保存策略,且開啟了自動抓取,所以列表頁只要用 CoreData 查詢即可。
UIApplication *application = [UIApplication sharedApplication]; id delegate = [application delegate]; self.xmppRosterManagedObjectContext = [delegate xmppRosterManagedObjectContext];
NSFetchRequest *request = [[NSFetchRequest alloc]
initWithEntityName:NSStringFromClass([XMPPUserCoreDataStorageObject class])];
NSSortDescriptor *sortD = [NSSortDescriptor sortDescriptorWithKey:@"jidStr" ascending:YES];
[request setSortDescriptors:@[sortD]];
self.fetchedResultsController = [[NSFetchedResultsController alloc]
initWithFetchRequest:request
managedObjectContext:self.xmppRosterManagedObjectContext
sectionNameKeyPath:nil
cacheName:nil];
self.fetchedResultsController.delegate = self;
NSError *error;
if (![self.fetchedResultsController performFetch:&error]) {
NSLog(@"%s %@", __FUNCTION__, [error localizedDescription]);
}
掛上 fetchedResultsController 的 delegate 之後,好友上下線導致 CoreData 內容變動時,列表會自動更新,不需要手動 reloadData。
mainThreadManagedObjectContext,在訊息量大時會拖慢 UI。建議背景 context 寫入、主 context 唯讀並透過 notification 合併。