iOS 开发中所需的数据基本都是来自网络,网络数据请求是 iOS 编程中必不可少的,应该熟练掌握网络请求.
网络请求方式有 :GET , POST , PUT ,DELETE 等,其中常用的就是 GET,POST . GET 和 POST 请求存在着不同,GET 将数据参数跟在 URL 后面,POST 参数放在 body 中,不可见.
数据请求方式分为同步请求和异步请求,其中常用的是异步请求,异步请求避免了因组线程阻塞而造成的崩溃.这里主要说下异步请求.
1.GET 同步请求 用 NSURLConnection 实现:
步骤:建立 request ----> 建立衔接请求数据 ------> 解析数据
代码:
1#PRagmamark --- get 同步 ---2- (IBAction)getOne:(id)sender {3self.allNewsArray =[[NSMutableArray alloc]init];4//url 地址5NSURL *url =[NSURL URLWithString:PATH];6//请求7NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:url];8//建立衔接请求数据9NSData *data =[NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];10//如果数据不为空就解析11if(data) {12NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:1error:nil];13//处理数据,用 model 存储14for(NSDictionary *dic1in[dic objectForKey:@"news"]) {15NewsModel *model =[[NewsModel alloc]init];16[model setValuesForKeysWithDictionary:dic1];17[self.allNewsArray addObject:model];18}1920}21}
2.GET 异步请求 BLOCK 形式用 NSURLConnection 实现
1#pragmamark --- get 异步请求 ---2- (IBAction)getTwo:(id)sender {34self.allNewsArray =[[NSMutableArray alloc]init];5//url 地址6NSURL *url =[NSURL URLWithString:PATH];7//请求8NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:url];9//默认是 get 方法,如果是 get 方法可以不写10[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError *_Nullable connectionError) {11if(data) {12NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0error:nil];13//处理数据,用 model 存储14for(NSDictionary *dic1in[dic objectForKey:@"news"]) {15NewsModel *model =[[NewsModel alloc]init];16[model setValuesForKeysWithDictionary:dic1];17[self.allNewsArray addObject:model];18}19}2021}];22}
3.POST 异步请求 BLOCK 形式:用 NSURLConnection 实现
1#pragmamark --- POST 异步 Block 形式 ---2- (IBAction)POSTBlock:(id)sender {34NSURL *URL = [NSURL URLWithString:@"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx"];5NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:URL];67//制作包体8NSString *param =@"date=20131129&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213";910NSData *data =[param dataUsingEncoding:NSUTF8StringEncoding];1112//设置请求方式13[request setHTTPMethod:@"POST"];14//设置 body15[request setHTTPBody:data];16[request setTimeoutInterval:60];171819//建立连接.请求数据20[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError *_Nullable connectionError) {2122//解析数据23if(data) {24NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0error:nil];25//处理数据,用 model 存储26for(NSDictionary *dic1in[dic objectForKey:@"news"]) {27NewsModel *model =[[NewsModel alloc]init];28[model setValuesForKeysWithDictionary:dic1];29[self.allNewsArray addObject:model];30}31}3233}];34}
4.POST 异步请求 delegate 形式:用 NSURLConnection 实现
1- (IBAction)POST_Delegate:(id)sender {23NSURL *URL = [NSURL URLWithString:@"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx"];45NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:URL];67//制作包体8NSString *param =@"date=20131129&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213";910NSData *data =[param dataUsingEncoding:NSUTF8StringEncoding];1112//设置请求方式13[request setHTTPMethod:@"POST"];14//设置请求 body15[request setHTTPBody:data];1617//建立连接请求数据18NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:requestdelegate:self];1920//启动请求21[conn start];22}2324- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{25NSLog(@"接收到响应");2627self.data =[NSMutableData data];2829}3031#pragmamark --- 接收数据的方法 ---32- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{33[self.data appendData:data];34}3536#pragmamark --- 结束传递数据 ---37- (void)connectionDidFinishLoading:(NSURLConnection *)connection{3839NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:self.data options:1error:nil];40NSLog(@"%@",dic);4142}434445- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{4647}
5.GET 异步请求session写法
1#pragmamark --- GET Session 写法 ---2- (IBAction)session:(id)sender {34//创建 session 对象5NSURLSession *session =[NSURLSession sharedSession];67NSURL *URL =[NSURL URLWithString:PATH];89NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:URL];1011NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError *_Nullable error) {1213if(data){14NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0error:nil];1516NSLog(@"%@",dic);17}18}];1920//开始请求 (一定要调用)21[task resume];22}
6.POST 异步请求 BLOCK 形式:用 NSURLSession 实现
1- (IBAction)POST_Session:(id)sender {23NSURL *URL = [NSURL URLWithString:@"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx"];45NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:URL];67//制作包体8NSString *param =@"date=20131129&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213";910NSData *data =[param dataUsingEncoding:NSUTF8StringEncoding];1112//设置请求方式13[request setHTTPMethod:@"POST"];14//设置请求 body15[request setHTTPBody:data];1617NSURLSession *session =[NSURLSession sharedSession];18NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError *_Nullable error) {19NSLog(@"%@",error);2021NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:1error:nil];22NSLog(@"%@",dic);23}];2425[task resume];26}