代碼地址:https://github.com/tom555cat/FenghuangFM.git
仿鳳凰FM iOS客戶端是出于3個(gè)目的
1>理解網(wǎng)絡(luò)請(qǐng)求
2>理解reactiveCocoa
3>理解MVVM
網(wǎng)絡(luò)請(qǐng)求
鳳凰FM的http請(qǐng)求返回?cái)?shù)據(jù)為JSON格式觉渴,可以用Chalse輕松抓取到這些http請(qǐng)求店溢,具體的請(qǐng)求信息在FenghuangFM/HTTPRequest下邊仔拟。
http請(qǐng)求返回為JSON格式的數(shù)據(jù)腿倚,解析JSON用到了MJExtension庫(kù)黔帕,JSON中有l(wèi)ist時(shí)聂沙,使用如下方式告知JSON中key為"audiolist"的list中每個(gè)元素是”Audio“類型怀泊。
[ActivityModel mj_setupObjectClassInArray:^NSDictionary *{
return @{
@"audiolist":@"Audio"
};
}];
另外返回的JSON中key可能會(huì)以"new"開(kāi)頭借尿,而我們定義模型時(shí)成員變量使用new開(kāi)頭會(huì)報(bào)錯(cuò)国旷,這時(shí)需要將JSON中的key轉(zhuǎn)換成模型中的成員變量名矛物,
[LeaderBoardData mj_setupReplacedKeyFromPropertyName:^NSDictionary *{
return @{
@"newsList":@"newList"
};
}];
reactiveCocoa
reactiveCocoa在這里的應(yīng)用和網(wǎng)絡(luò)請(qǐng)求結(jié)合在了一起,載入主頁(yè)時(shí)跪但,需要發(fā)出兩個(gè)http請(qǐng)求履羞,等待這兩個(gè)請(qǐng)求都回返結(jié)果后再繼續(xù)下一步峦萎,reactiveCocoa可以非常簡(jiǎn)單地完成這個(gè)動(dòng)作,
MainFeatureViewModel.m
- (void)refreshDataSource
{
@weakify(self);
RACSignal *signalFocus = [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
@strongify(self);
[self requestFocusList:^{
[subscriber sendNext:nil];
}];
return nil;
}];
RACSignal *signalRest = [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
@strongify(self);
[self requestRest:^{
[subscriber sendNext:nil];
}];
return nil;
}];
[[RACSignal combineLatest:@[signalFocus,signalRest]] subscribeNext:^(id x) {
@strongify(self);
[(RACSubject *)self.updateContentSignal sendNext:nil];
}];
}
MVVM
MVVM解放了MVC框架中繁雜龐大的ViewController忆首。原來(lái)的ViewController中包含了"Views+業(yè)務(wù)"爱榔,現(xiàn)在MVVM使用ViewModel將業(yè)務(wù)這部分轉(zhuǎn)移了出來(lái),瞬間使ViewController的體量降了下來(lái)糙及∠暧模看一下主頁(yè)用到的一個(gè)ViewModel:
MainFeatureViewModel.h
@interface MainFeatureViewModel : NSObject
@property (nonatomic, readonly) RACSignal *updateContentSignal;
@property (nonatomic, strong) MainFeatureModel *featureModel;
@property (nonatomic, strong) RecommendModel *recommendModel;
- (void)refreshDataSource;
- (NSInteger)numberOfSections;
- (NSInteger)numberOfItemsInSection:(NSInteger)section;
- (CGFloat)heightForRowAtIndex:(NSIndexPath *)indexPath;
@end
數(shù)據(jù)模型MainFeatureModel和RecommendModel相關(guān)的操作脫離了VC轉(zhuǎn)移到了這里,在MainFeatureController中浸锨,只要通過(guò)viewModel屬性就可以獲取到數(shù)據(jù)唇聘。
@property (nonatomic, strong) MainFeatureViewModel *viewModel;