1.先下载AFNETWorking三方
2.导入到自己的程序中
3.在程序中新建文件AFNModel
在AFNModel.h 中
//定义block
typedef void(^NETBLOCK) (id result);
@interface AFNModel : BaseModel
//GET
+ (void)GETWithURL:(NSString *)str completion:(NETBLOCK)netblock;
@end
在AFNModel.m中
+ (void)GETWithURL:(NSString *)str completion:(NETBLOCK)netblock
{
//中文转码
NSString *newStr = [strstringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSetcharacterSetWithCharactersInString:str]];
//创建AFN管理
AFHTTPSessionManager *seccionManager = [AFHTTPSessionManagermanager];
seccionManager.responseSerializer = [AFHTTPResponseSerializerserializer];
//进行get请求
[seccionManager GET:newStr parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
NSLog(@"%lld", downloadProgress.totalUnitCount);
} success:^(NSURLSessionDataTask *_Nonnull task, id _Nullable responseObject) {
//JSON解析
id result = [NSJSONSerializationJSONObjectWithData:responseObject options:NSJSONReadingMutableContainerserror:nil];
netblock(result);
} failure:^(NSURLSessionDataTask *_Nullable task, NSError *_Nonnull error) {
NSLog(@"%@", error);
}];
}
[AFNModel GETWithURL:@"网址" completion:^(id result) {