您的位置:首页 > 其它

弃用的异步get和post方法之代理方法

2016-05-11 17:09 363 查看
#import "ViewController.h"
#import "Header.h"

@interface ViewController () <NSURLConnectionDataDelegate>

/**
*  用来存储数据
*/
@property (nonatomic, strong) NSMutableData *resultData;

@property (nonatomic, strong) NSMutableArray *dataArray;

@end

@implementation ViewController

// 懒加载
- (NSMutableArray *)dataArray {

if (!_dataArray) {
_dataArray = [NSMutableArray array];
}
return _dataArray;
}

- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}

#pragma mark - get异步请求
- (IBAction)getAsynchronousRequset:(UIButton *)sender {

// 1.创建url
NSURL *url = [NSURL URLWithString:GET_URL];

// 2.创建请求
NSURLRequest *request = [NSURLRequest requestWithURL:url];

// 使用delegate实现
[NSURLConnection connectionWithRequest:request delegate:self];

}

#pragma mark - 代理方法
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {

// 初始化数据
self.resultData = [NSMutableData data];

}

// 开始接收数据(这个方法会重复执行,得到的每段数据拼接在一起就可以了)
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {

[self.resultData appendData:data];
}

// 结束服务器
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {

// 进行数据解析
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:self.resultData options:NSJSONReadingAllowFragments error:nil];
NSLog(@"%@", dic);
}

#pragma mark - post异步请求
- (IBAction)postAsynchronousRequset:(UIButton *)sender {

// 1.创建url
NSURL *url = [NSURL URLWithString:POST_URL];

// 2.创建请求
NSMutableURLRequest *mutableRequest = [NSMutableURLRequest requestWithURL:url];

// 2.5.设置body
// 创建一个连接字符串(这个内容在以后的开发中接口文档都有标注)
NSString *dataStr = POST_BODY;

// 对连接字符串进行编码【这一步千万不能忘记】
NSData *postData = [dataStr dataUsingEncoding:NSUTF8StringEncoding];

// 设置请求格式为post请求【在这里POST必须大写】
[mutableRequest setHTTPMethod:@"POST"];

// 设置请求体(body)
[mutableRequest setHTTPBody:postData];

// 代理方法
[NSURLConnection connectionWithRequest:mutableRequest delegate:self];
}

#pragma mark - 代理方法
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {

// 初始化数据
self.resultData = [NSMutableData data];

}

// 开始接收数据(这个方法会重复执行,得到的每段数据拼接在一起就可以了)
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {

[self.resultData appendData:data];
}

// 结束服务器
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {

// 进行数据解析
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:self.resultData options:NSJSONReadingAllowFragments error:nil];
NSLog(@"%@", dic);
}

@end
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: