一、前言:工程是MVC的,采用AFNetworking框架进行网络数据请求
MBProgressHUD框架进行弹窗提示
二、定义网络请求
1.直接在Model层定义一个类
例如DCCardModel
#import <Foundation/Foundation.h>
@interface DCCardModel : NSObject
@property(nonatomic,copy)NSString *update;//
@property(nonatomic,copy)NSString *url;
//定义两种方法
+ (NSURLSessionDataTask *)queryCardWithParameters:(NSDictionary *)parameters completion:(responseArrayWithPaginationBlock)completion;
+ (void)loadCardCompletion:(responseArrayBlock)completion;
@end
属性解释
因为发起POST请求:返回结果是{"update":"2","url":"http://s16.sinaimg.cn/large/005vePOgzy70Rd3a9pJdf&690"}
上面的属性就是根据这个定义的
方法解释:
- (void)loadCardCompletion:(responseArrayBlock)completion;
首先它是一个类方法,responseArrayBlock是一个Block,这个Block定义在一个公共的文件,例如AppConfig.h定义
typedef void (^responseArrayBlock)(NSArray *array, NSString *error);
方法实现
+ (void)loadCardCompletion:(responseArrayBlock)completion
{
[[APIClient sharedClient] POST:@"http://127.0.0.1/getJson.php"
parameters:nil
progress:^(NSProgress * _Nonnull uploadProgress) {
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(@"请求结果:%@",responseObject);
//block回调
completion(nil,data);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
completion(nil, error.localizedDescription);
}];
}
[[APIClient sharedClient] 是对Afnetwork的封装方法
在APIClient.h类中定义一个请求单例
- (instancetype)sharedClient;
.m实现
+ (instancetype)sharedClient {
static APIClient *_sharedClient = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_sharedClient = [APIClient manager];
_sharedClient.requestSerializer = [AFJSONRequestSerializer serializer];
_sharedClient.responseSerializer = [ResponseSerializer serializer];
//设定请求超时时间
[_sharedClient.requestSerializer willChangeValueForKey:@"timeoutInterval"];
_sharedClient.requestSerializer.timeoutInterval = 60.f;
[_sharedClient.requestSerializer didChangeValueForKey:@"timeoutInterval"];
((AFJSONResponseSerializer *)_sharedClient.responseSerializer).removesKeysWithNullValues = YES;
_sharedClient.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/html", @"text/javascript", @"text/plain", nil];
});
return _sharedClient;
}
三、使用
viewController.m定义一个方法,加载数据
#pragma mark - 请求卡类型数据
- (void)loadData
{
//先走一个动画,提示用户正在加载数据
[MBProgressHUD showCustomLoadingHub:[MBProgressHUDCoustomView hotelLoadingGifView]];
@weakify(self);
[DCCardModel loadCardCompletion:^(NSArray *array, NSString *error) {
@strongify(self)
//请求到数据的时候,就隐藏动画
[MBProgressHUD hideHUD];
if (!error) {
if (array.count > 0) {
NSLog(@"do something!!!!!!!!!!");
}
} else {
[MBProgressHUD showHUDWithFailedText:error];
}
}];
}
网友评论