你的位置:首页 > 操作系统

[操作系统]iOS 网络编程


iOS 开发中所需的数据基本都是来自网络,网络数据请求是 iOS 编程中必不可少的,应该熟练掌握网络请求.

网络请求方式有 :GET , POST , PUT ,DELETE 等,其中常用的就是 GET,POST . GET 和 POST 请求存在着不同,GET 将数据参数跟在 URL 后面,POST 参数放在 body 中,不可见.

数据请求方式分为同步请求和异步请求,其中常用的是异步请求,异步请求避免了因组线程阻塞而造成的崩溃.这里主要说下异步请求.

1.GET 同步请求 用 NSURLConnection 实现:

  步骤:建立 request ----> 建立衔接请求数据 ------> 解析数据

代码:

 1 #pragma mark --- get 同步 --- 2 - (IBAction)getOne:(id)sender { 3   self.allNewsArray = [[NSMutableArray alloc]init]; 4   //url 地址 5   NSURL *url = [NSURL URLWithString:PATH]; 6   //请求 7   NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; 8   //建立衔接请求数据 9   NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];10   //如果数据不为空就解析11   if (data) {12     NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:1 error:nil];13     //处理数据,用 model 存储14     for (NSDictionary *dic1 in [dic objectForKey:@"news"]) {15       NewsModel *model = [[NewsModel alloc]init];16       [model setValuesForKeysWithDictionary:dic1];17       [self.allNewsArray addObject:model];18     }19     20   }21 }

2.GET 异步请求 BLOCK 形式 用 NSURLConnection 实现

 1 #pragma mark --- get 异步请求 --- 2 - (IBAction)getTwo:(id)sender { 3    4   self.allNewsArray = [[NSMutableArray alloc]init]; 5   //url 地址 6   NSURL *url = [NSURL URLWithString:PATH]; 7   //请求 8   NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; 9  //默认是 get 方法,如果是 get 方法可以不写10   [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {11     if (data) {12       NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];13       //处理数据,用 model 存储14       for (NSDictionary *dic1 in [dic objectForKey:@"news"]) {15         NewsModel *model = [[NewsModel alloc]init];16         [model setValuesForKeysWithDictionary:dic1];17         [self.allNewsArray addObject:model];18       }19     }20     21   }];22 }

3.POST 异步请求 BLOCK 形式:用 NSURLConnection 实现

 

 1 #pragma mark --- POST 异步 Block 形式 --- 2 - (IBAction)POSTBlock:(id)sender { 3    4   NSURL *URL = [NSURL URLWithString:@"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx"]; 5   NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL]; 6    7   //制作包体 8   NSString *param = @"date=20131129&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213"; 9   10   NSData *data = [param dataUsingEncoding:NSUTF8StringEncoding];11   12   //设置请求方式13   [request setHTTPMethod:@"POST"];14   //设置 body15   [request setHTTPBody:data];16   [request setTimeoutInterval:60];17   18   19   //建立连接.请求数据20   [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {21     22     //解析数据23     if (data) {24       NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];25       //处理数据,用 model 存储26       for (NSDictionary *dic1 in [dic objectForKey:@"news"]) {27         NewsModel *model = [[NewsModel alloc]init];28         [model setValuesForKeysWithDictionary:dic1];29         [self.allNewsArray addObject:model];30       }31     }32     33   }];34  }

 

 

 

4.POST 异步请求 delegate 形式:用 NSURLConnection 实现

 

 1 - (IBAction)POST_Delegate:(id)sender { 2    3   NSURL *URL = [NSURL URLWithString:@"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx"]; 4    5   NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL]; 6    7   //制作包体 8   NSString *param = @"date=20131129&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213"; 9   10   NSData *data = [param dataUsingEncoding:NSUTF8StringEncoding];11   12   //设置请求方式13   [request setHTTPMethod:@"POST"];14   //设置请求 body15   [request setHTTPBody:data];16   17   //建立连接请求数据18   NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self];19   20   //启动请求21   [conn start];22   }23 24 - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{25   NSLog(@"接收到响应");26   27   self.data = [NSMutableData data];28   29 }30 31 #pragma mark --- 接收数据的方法 ---32 - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{33   [self.data appendData:data];34 }35 36 #pragma mark --- 结束传递数据 ---37 - (void)connectionDidFinishLoading:(NSURLConnection *)connection{38   39   NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:self.data options:1 error:nil];40   NSLog(@"%@",dic);41   42 }43 44 45 - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{46   47 }

 

 

 

5.GET 异步请求 SESSION 写法

 

 1 #pragma mark --- GET Session 写法 --- 2 - (IBAction)session:(id)sender { 3    4   //创建 session 对象 5   NSURLSession *session = [NSURLSession sharedSession]; 6    7   NSURL *URL = [NSURL URLWithString:PATH]; 8    9   NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];10   11   NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {12     13     if(data){14       NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];15       16       NSLog(@"%@",dic);17     }18   }];19   20   //开始请求 (一定要调用)21   [task resume];22 }

 

6.POST 异步请求 BLOCK 形式:用 NSURLSession 实现

 

 1 - (IBAction)POST_Session:(id)sender { 2    3   NSURL *URL = [NSURL URLWithString:@"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx"]; 4    5   NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL]; 6    7   //制作包体 8   NSString *param = @"date=20131129&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213"; 9   10   NSData *data = [param dataUsingEncoding:NSUTF8StringEncoding];11   12   //设置请求方式13   [request setHTTPMethod:@"POST"];14   //设置请求 body15   [request setHTTPBody:data];16   17   NSURLSession *session = [NSURLSession sharedSession];18   NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {19     NSLog(@"%@",error);20     21     NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:1 error:nil];22     NSLog(@"%@",dic);23   }];24   25   [task resume];26 }