標籤:
上一篇文章,我們討論了調試和好友模組,這一篇,在引入了好友模組後,我們來說說好友名單的顯示。
還記得在上一篇中,我們把自動拉去好友名單給關掉了,所以,我們選擇在控制器的-(void)viewDidLoad;中手動拉取好友名單,並且添加代理。
[[XMPPManager sharedInstance].xmppRoster fetchRoster];[[XMPPManager sharedInstance].xmppRoster addDelegate:self delegateQueue:dispatch_get_main_queue()];[[XMPPManager sharedInstance].xmppStream addDelegate:self delegateQueue:dispatch_get_main_queue()];
// 好友同步結束- (void)xmppRosterDidEndPopulating:(XMPPRoster *)sender { NSLog(@"好友同步結束,查詢資料庫"); dispatch_async(dispatch_get_main_queue(), ^{ [self queryFriendList]; });}// 尋找到好友- (void)xmppRoster:(XMPPRoster *)sender didReceiveRosterPush:(XMPPIQ *)iq { dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ [self queryFriendList]; });}#pragma mark XMPPStreamDelegate- (void)xmppStream:(XMPPStream *)sender didReceivePresence:(XMPPPresence *)presence { //這個if成立的時候說明對方拒絕或者刪除了你 if ([presence.type isEqualToString:@"unsubscribed"]) { [[XMPPManager sharedInstance].xmppRoster removeUser:presence.from]; }}
手動拉取好友名單之後,會調取上面第一個代理方法,我們在這個方法裡面在本地做一次好友尋找。等伺服器端收到好友名單後,會調用第二個代理方法,病將列表存入本地coredata中,所以,我們再從本地尋找一次。
第三個代理方法,是收到presence訊息後的調用。我們在裡面處理收到好友請求被拒絕或者對方刪除(即取消訂閱),這邊的操作是將好友remove掉。
接下來就是最重要的本地coredata尋找功能,-(void)queryFriendList函數。
從coredata中尋找資料分為三步,建立尋找請求,定位實體,設定資料排序或篩選模式。這些代碼並不需要我們寫,蘋果有個代碼塊可以供我們用。以下就是:
把這段代碼拖到我們需要的地方就行。
- (void)queryFriendList { NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; XMPPRosterCoreDataStorage *storage = [XMPPRosterCoreDataStorage sharedInstance]; NSEntityDescription *entity = [NSEntityDescription entityForName:@"XMPPUserCoreDataStorageObject" inManagedObjectContext:storage.mainThreadManagedObjectContext]; [fetchRequest setEntity:entity]; // Specify criteria for filtering which objects to fetch// NSPredicate *predicate = [NSPredicate predicateWithFormat:@"subscription = ‘both‘"];// [fetchRequest setPredicate:predicate]; // Specify how the fetched objects should be sorted NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"jidStr" ascending:YES]; [fetchRequest setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]]; NSError *error = nil; NSArray *fetchedObjects = [storage.mainThreadManagedObjectContext executeFetchRequest:fetchRequest error:&error]; if (fetchedObjects == nil) { // } self.friendList = fetchedObjects; [self.tableView reloadData];}
拖完之後,修改些類名,排序和篩選方式,再做些個人化操作,就可以了。
這裡需要注意的是,我們得到fetchedObjects這些結果之後,可以立刻轉為我們需要的Model,用起來方便,數組中的每個對象,都是
XMPPUserCoreDataStorageObject對象,進入標頭檔中看,更加清楚。
接下來,我們調試一下。
運行程式。
先在“訊息”應用中添加好友。
程式代理方法
- (void)xmppStream:(XMPPStream *)sender didReceivePresence:(XMPPPresence *)presence;
收到訂閱請求。
<presence xmlns="jabber:client" type="subscribe" to="[email protected]" from="[email protected]"></presence>
來自[email protected]的,type為subscribe的訂閱請求。
我們在上一篇中講過,收到後自動同意。我們切換到好友名單介面
成功!zhangsan已經存在我們的好友名單內~
這一篇我們討論了好友名單,下一篇我們開始聊天的話題,下次見。
XMPP即時通訊交流群140147825,歡迎大家來交流~我們是一起寫代碼的弟兄~周末愉快~
iOS開發--XMPPFramework--好友名單(五)