iOS激情详解之URL同步,异步连接
2015-09-17 13:19
176 查看
// // GetViewController.m // NSURLRequest // // Created by WDX on 15/9/11. // Copyright (c) 2015年 WDongXu. All rights reserved. // #import "GetViewController.h" @interface GetViewController ()<NSURLConnectionDataDelegate,NSURLConnectionDelegate> //遵守协议// 加载错误时用NSURLConnectionDelegate // 声明一个可变的data,用来凭借完整的数据 @property (nonatomic ,retain)NSMutableData *data; // 声明一个链接属性,用于终止网络请求 @property (nonatomic, retain)NSURLConnection *connection ; @end
</pre><pre name="code" class="objc">@implementation GetViewController - (void)dealloc { // 如果本页面被销毁 那么要终止网络请求 [_connection cancel]; [_connection release]; [ _data release]; [super dealloc]; } - (void)viewDidLoad { [super viewDidLoad]; self.navigationItem.title = @“子敬"; [self addBarButton]; } - (void)addBarButton { self.view.backgroundColor = [UIColor redColor]; UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithTitle:@"同步" style:(UIBarButtonItemStylePlain) target:self action:@selector(actionLeftButton:)]; self.navigationItem.leftBarButtonItem = leftButton; [leftButton release]; UIBarButtonItem *rightButton = [[UIBarButtonItem alloc] initWithTitle:@"异步" style:(UIBarButtonItemStylePlain) target:self action:@selector(actionRightButton:)]; self.navigationItem.rightBarButtonItem = rightButton; [rightButton release]; }
// GET同步请求 - (void)actionLeftButton:(UIBarButtonItem *)button { NSLog(@"同步"); // 1,创建网址对象 NSString *oldUrl = kSearchURL; // 2,如果你请求的网址中带有中文必须进行重新编码,一般用NSUTF8StringEncoding NSString *newUrl = [oldUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; // 把字符串变成网址对象 NSURL *url = [NSURL URLWithString:newUrl]; // 发出一个请求 // cachePolicy 缓存策略一般选择默选择策略 // timeoutInterval 请求超时时间设置30秒 NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:(NSURLRequestUseProtocolCachePolicy) timeoutInterval:30.0]; // 默认是get请求:NSURLRequest 如果要是设置的话就是可变请求 // 设置请求路径 [request setHTTPMethod:@"GET"]; // 建立链接 // 接收二进制数据 // response服务器返回的描述服务器的数据 // error 连接错误信息 // 你不需要的话描述服务器的数据和错误信息可以直接填写nil NSURLResponse *response = nil; NSError *error = nil; NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; // NSLog(@"%@",response); // 转换成咱们需要的数据 json数据 NSMutableDictionary *dataDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil]; NSLog(@"%@", dataDic); }
// GET异步请求 - (void)actionRightButton:(UIBarButtonItem *)button { // 1,如果你请求的网址中带有中文 必须进行重新编码 一般用NSUTF8StringEncoding NSString *newUrl = [kImageURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; // 2,利用网址字符串创建一个网址对象 NSURL *url = [NSURL URLWithString:newUrl]; // 3,利用网址对象创建一个请求 NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:(NSURLRequestUseProtocolCachePolicy) timeoutInterval:30.0]; // 4,设置请求类型 [request setHTTPMethod:@"GET"]; // 前四步与同步请求一样 #pragma mark -- 异步请求利用 Block方法: // 建立一个异步请求的链接 [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) { // 异步请求相当于开启一个子线程去加载数据 // 数据加载完成调用block回到主线程 // 打印是否主线程 NSLog(@"%d", [NSThread isMainThread]); }]; #pragma mark -- 异步请求利用代理方法实现 // 利用请求创建一个链接 注意:同步异步有区别 // 设置协议 遵守的协议名字:NSURLConnectionDataDelegate self.connection = [NSURLConnection connectionWithRequest:request delegate:self]; // 开启异步请求 [self.connection start]; }
#pragma mark— NSURLConnectionDataDelegate - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { // 触发方法,链接成功,初始化可变data self.data = [NSMutableData data]; NSLog(@"接收到服务器数据,说明链接成功"); } - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { // 拼接data [self.data appendData:data]; NSLog(@"接收数据时触发"); } - (void)connectionDidFinishLoading:(NSURLConnection *)connection { // 该方法触发说明data已经完整了,接下来可以解析数据 // 转换成咱们需要的数据,json数据 NSMutableDictionary *dataDic = [NSJSONSerialization JSONObjectWithData:self.data options:NSJSONReadingMutableContainers error:nil]; NSLog(@"已经完成加载"); } - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { NSLog(@"查看错误信息"); } @end
相关文章推荐
- IOS 取消表格单元格 TableViewCell 去掉高亮状态 点击Cell取消选择状态
- 1、BIOS中的虚拟化技术
- IOS-TextField知多少
- iOS 支付宝 的学习总结
- iOS9AdaptationTips
- iOS开发 iOS9适配问题
- ffmpeg在iOS的使用 - iFrameExtractor源码解析
- iOS 警告收录及科学快速的消除方法
- iOS 集成银联支付(绕过文档的坑,快速集成)
- iOS工程集成支付宝错误symbol(s) not found for architecture x86_64
- 我的第一篇博客
- Xcode7 更新后三方框架丢失。项目报错解决方法
- IOS第一天-新浪微博 - 框架的搭建
- iOS工程集成支付宝错误Undefined symbols for architecture armv7
- iOS 9 适配系列教程
- IOS开发之----property详解
- ios各种动画效果
- IOS 调用摄像头拍照
- iOS开发:MRC和ARC
- iOS开发~CocoaPods安装和使用