前言 :
各位同学大家好, 有段时间没有给各位更新文章了。具体多久我也不记得了 。今天给大家分享下 ios里面的网络请求 几种方式 。
需要用到的三方库
target 'bosstab' do
pod 'AFNetworking'
end
-
第一种方式 原生网络请求
// 获取菜单信息
- (void)loadListMenuWithFinishBlock:(GTListLoaderMenuFinishBlock)finishBlock{
NSLog(@"请求数据menu ");
NSString *urlString = @"http://www.qubaobei.com/ios/cf/dish_list.php?stage_id=1&limit=20&page=1";
NSError * _Nullable error;
NSURL *listURL = [NSURL URLWithString:urlString];
__weak typeof(self)weakSelf=self;
NSURLSession * session= [NSURLSession sharedSession];
NSURLSessionDataTask * dataTask= [session dataTaskWithURL:listURL completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
__strong typeof(weakSelf)strongSelf=weakSelf;
NSError * jsonError;
id jsonobject=[NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonError];
#warning 类型的检查
NSArray *dataArray = [jsonobject objectForKey:@"data"];
NSMutableArray * listItemArray=@[].mutableCopy;
for (NSDictionary * info in dataArray) {
Menuitem * listItem= [[Menuitem alloc]init];
[listItem configWithDictionary:info];
[listItemArray addObject:listItem];
}
dispatch_async(dispatch_get_main_queue(), ^{
if(finishBlock){
finishBlock(error==nil,listItemArray.copy);
}
});
}];
[dataTask resume];
}
-
第二种方式 afnetwork
// 获取菜单信息
- (void)loadListMenuWithAfnetworkFinishBlock:(GTListLoaderMenuFinishBlock)finishBlock{
NSLog(@"请求数据menu ");
NSString *urlString = @"http://www.qubaobei.com/ios/cf/dish_list.php?stage_id=1&limit=20&page=1";
NSError * _Nullable error;
[[AFHTTPSessionManager manager]GET:urlString parameters:nil headers:nil progress:^(NSProgress * _Nonnull downloadProgress) {
NSLog(@"");
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(@"");
NSLog(@"请求成功---%@",responseObject);
NSArray *dataArray = [responseObject objectForKey:@"data"];
NSMutableArray * listItemArray=@[].mutableCopy;
for (NSDictionary * info in dataArray) {
Menuitem * listItem= [[Menuitem alloc]init];
[listItem configWithDictionary:info];
[listItemArray addObject:listItem];
}
dispatch_async(dispatch_get_main_queue(), ^{
if(finishBlock){
finishBlock(error==nil,listItemArray.copy);
}
});
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"请求失败");
NSLog(@"");
}];
}
最后总结:
ios 的原生的网络请求,
网友评论