增加搜索好友功能 由于 XMPP 不能直接查詢到數(shù)據(jù)庫中已注冊的用戶,這里使用HTTP請求來查詢好友,由于沒有接口,就用豆瓣音樂的搜索音樂的API模擬吧。
1.首先快速搭建一個響應是的所搜框
<pre>
[[self.search.rac_textSignal
doNext:^(NSString *x) {
@strongify(self)
if (x.length>2) {
self.search.backgroundColor=[UIColor whiteColor];
}else{
self.search.backgroundColor = [UIColor yellowColor];
}
}]
</pre>
2.創(chuàng)建一個信號將搜索的結(jié)果返回 使用AFNetworking 和MJExtension轉(zhuǎn)模型
<pre>
- (RACSignal *)signalForSearchWithText:(NSString *)text {
return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
NSMutableDictionary *parrameter = [NSMutableDictionary dictionary];
parrameter[@"q"] = text;
parrameter[@"count"] = @"10";
[mgr GET:@"https://api.douban.com/v2/music/search" parameters:parrameter progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSArray *musices = [Music mj_objectArrayWithKeyValuesArray:responseObject[@"musics"]];
[subscriber sendNext:musices];
[subscriber sendCompleted];
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
[subscriber sendError:error];
}];
return nil;
}];
}
</pre>
3.接著search繼續(xù)
這里需要使用 flattenMap 做信號映射 并設置數(shù)據(jù)源
<pre>
[[[[self.search.rac_textSignal
doNext:^(NSString *x) {
@strongify(self)
if (x.length>2) {
self.search.backgroundColor=[UIColor whiteColor];
}else{
self.search.backgroundColor = [UIColor yellowColor];
}
}]
throttle:1]
flattenMap:^RACStream *(NSString *value) {
NSLog(@"%@",value);
@strongify(self)
return [self signalForSearchWithText:value];
}]
subscribeNext:^(NSArray *x) {
@strongify(self)
self.musices = x;
[self.tableView reloadData];
} error:^(NSError *error) {
NSLog(@"%@",error);
}];
</pre>
注意到上面的 throttle:1 可以延遲一秒后在執(zhí)行 訪問頻繁豆瓣會拒絕的......
在基礎(chǔ)教程中有一個異步加載圖片的signal方法
<pre>
/**
- 異步加載圖片使用 [RACScheduler schedulerWithPriority:RACSchedulerPriorityBackground] 方法點開方法可以看到就是 GCD
*/
-(RACSignal *)signalForImage:(NSString *)imageUrl {
RACScheduler *scheduler = [RACScheduler schedulerWithPriority:RACSchedulerPriorityBackground];
return [[RACSignal createSignal:^RACDisposable *(id subscriber) {
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:imageUrl]];
UIImage *image = [UIImage imageWithData:data];
[subscriber sendNext:image];
[subscriber sendCompleted];
return nil;
}]
subscribeOn:scheduler];
}
</pre>
在cell內(nèi)執(zhí)行 , 刷新UI時注意線程
<pre>
[[[[self signalForImage:music.image]
takeUntil:cell.rac_prepareForReuseSignal]
deliverOn:[RACScheduler mainThreadScheduler]]
subscribeNext:^(UIImage *x) {
cell.imageView.image = x;
}];
</pre>
不過用SDWebImage也可以 思路一樣 SDWebImage 更全面一些 同樣最后吧查詢方法封裝在XMPPTool里方便管理
運行:
界面丑爆了見諒 完整Dome