iOS 网络编程

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

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

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

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

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

代码:

 #pragma mark --- get 同步 ---
- (IBAction)getOne:(id)sender {
self.allNewsArray = [[NSMutableArray alloc]init];
//url 地址
NSURL *url = [NSURL URLWithString:PATH];
//请求
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
//建立衔接请求数据
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
//如果数据不为空就解析
if (data) {
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options: error:nil];
//处理数据,用 model 存储
for (NSDictionary *dic1 in [dic objectForKey:@"news"]) {
NewsModel *model = [[NewsModel alloc]init];
[model setValuesForKeysWithDictionary:dic1];
[self.allNewsArray addObject:model];
} }
}

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

 #pragma mark --- get 异步请求 ---
- (IBAction)getTwo:(id)sender { self.allNewsArray = [[NSMutableArray alloc]init];
//url 地址
NSURL *url = [NSURL URLWithString:PATH];
//请求
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
//默认是 get 方法,如果是 get 方法可以不写
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
if (data) {
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options: error:nil];
//处理数据,用 model 存储
for (NSDictionary *dic1 in [dic objectForKey:@"news"]) {
NewsModel *model = [[NewsModel alloc]init];
[model setValuesForKeysWithDictionary:dic1];
[self.allNewsArray addObject:model];
}
} }];
}

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

 #pragma mark --- POST 异步 Block 形式 ---
- (IBAction)POSTBlock:(id)sender { NSURL *URL = [NSURL URLWithString:@"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL]; //制作包体
NSString *param = @"date=20131129&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213"; NSData *data = [param dataUsingEncoding:NSUTF8StringEncoding]; //设置请求方式
[request setHTTPMethod:@"POST"];
//设置 body
[request setHTTPBody:data];
[request setTimeoutInterval:]; //建立连接.请求数据
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) { //解析数据
if (data) {
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options: error:nil];
//处理数据,用 model 存储
for (NSDictionary *dic1 in [dic objectForKey:@"news"]) {
NewsModel *model = [[NewsModel alloc]init];
[model setValuesForKeysWithDictionary:dic1];
[self.allNewsArray addObject:model];
}
} }];
}

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

 - (IBAction)POST_Delegate:(id)sender {

     NSURL *URL = [NSURL URLWithString:@"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx"];

     NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];

     //制作包体
NSString *param = @"date=20131129&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213"; NSData *data = [param dataUsingEncoding:NSUTF8StringEncoding]; //设置请求方式
[request setHTTPMethod:@"POST"];
//设置请求 body
[request setHTTPBody:data]; //建立连接请求数据
NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self]; //启动请求
[conn start];
} - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
NSLog(@"接收到响应"); self.data = [NSMutableData data]; } #pragma mark --- 接收数据的方法 ---
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
[self.data appendData:data];
} #pragma mark --- 结束传递数据 ---
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{ NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:self.data options: error:nil];
NSLog(@"%@",dic); } - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{ }

5.GET 异步请求 SESSION 写法

 #pragma mark --- GET Session 写法 ---
- (IBAction)session:(id)sender { //创建 session 对象
NSURLSession *session = [NSURLSession sharedSession]; NSURL *URL = [NSURL URLWithString:PATH]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL]; NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { if(data){
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options: error:nil]; NSLog(@"%@",dic);
}
}]; //开始请求 (一定要调用)
[task resume];
}

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

 - (IBAction)POST_Session:(id)sender {

     NSURL *URL = [NSURL URLWithString:@"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx"];

     NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];

     //制作包体
NSString *param = @"date=20131129&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213"; NSData *data = [param dataUsingEncoding:NSUTF8StringEncoding]; //设置请求方式
[request setHTTPMethod:@"POST"];
//设置请求 body
[request setHTTPBody:data]; NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSLog(@"%@",error); NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options: error:nil];
NSLog(@"%@",dic);
}]; [task resume];
}
上一篇:xml 个人练习2


下一篇:Use LiveCD to acquire images from a VM