傳統(tǒng)網(wǎng)絡(luò)請(qǐng)求封裝
-(void)requestDataWithUrl:(NSString *)url dict:(NSDictionary *)parameters andSucc:(void (^)(id response))succBlock andFail:(void (^)(NSError *error))failBlock{
AFHTTPSessionManager * manager = [AFHTTPSessionManager manager];
//這里添加一些請(qǐng)求頭,userAgent,超時(shí)時(shí)間
[manager GET:url parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
if (succBlock) {
succBlock(responseObject);
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
if(failBlock){
failBlock(error);
}
}];
}
ReactiveCocoa網(wǎng)絡(luò)請(qǐng)求封裝
關(guān)于傳統(tǒng)的網(wǎng)絡(luò)請(qǐng)求的封裝曲掰,大家都很熟悉垃杖,這里就不再贅述了符衔。RAC
和MVVM
完美融合,所以使用MVVM
的小伙伴一旦進(jìn)入RAC
的世界就再也走不出來了糟袁。下面讓我們一起走入他的世界吧判族。
-(RACSignal *)requestManagerWithUrl:(NSString *)url params:(NSDictionary *)params{
AFHTTPSessionManager * manager = [AFHTTPSessionManager manager];
//這里添加一些請(qǐng)求頭,userAgent,超時(shí)時(shí)間
return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber> _Nonnull subscriber) {
[manager GET:url parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary * _Nullable responseObject) {
[subscriber sendNext:responseObject[@"data"]];
[subscriber sendCompleted];
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
[subscriber sendNext:error];
}];
return nil;
}];
}
這里我們所有的返回結(jié)果都根據(jù)信號(hào)的方式返回了项戴,不再需要在一個(gè)方法里面寫一堆block
形帮。當(dāng)然接下來講的就是如何使用了,viewModel
中處理網(wǎng)絡(luò)請(qǐng)求
-(RACCommand *)requestCommand{
if (!_requestCommand) {
_requestCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal * _Nonnull(id _Nullable input) {
return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber> _Nonnull subscriber) {
//網(wǎng)絡(luò)請(qǐng)求
[[LQNetWorkManager requestManagerWithUrl:@"" params:@{}] subscribeNext:^(id _Nullable x) {
/*正常請(qǐng)求在這里面處理
*這里處理一些網(wǎng)絡(luò)返回值 json-->model
*處理數(shù)據(jù)后subscriber返回
*/
[subscriber sendNext:x];
[subscriber sendCompleted];
} error:^(NSError * _Nullable error) {
[subscriber sendError:error];
}];
return nil;
}];
}];
}
return _requestCommand;
}
在VC中回調(diào)
- (void)viewDidLoad {
[super viewDidLoad];
[self.viewModel.requestCommand.executionSignals.switchToLatest subscribeNext:^(id _Nullable x) {
//網(wǎng)絡(luò)請(qǐng)求完成
NSLog(@"%@",x);
}];
[self.viewModel.requestCommand.errors subscribeNext:^(id _Nullable x) {
//網(wǎng)絡(luò)請(qǐng)求出錯(cuò)處理
NSLog(@"信號(hào)錯(cuò)誤");
}];
[self.viewModel.requestCommand execute:@""];//發(fā)送網(wǎng)絡(luò)請(qǐng)求
}
這樣一個(gè)網(wǎng)絡(luò)請(qǐng)求就完成了周叮,未完待續(xù)