网络请求
请求网络数据,常见有两种方式
- 同步
- 异步
在iOS8中已经弃用了NSURLConnection,而启用NSURLSession,同时在iOS9中启用了https加密,所以和以往的方式不仅相同,下边做些整理
同步请求 1
//通过一个网址直接拿到数据,然后JSON解析即可,这种属于同步请求,阻塞主线程,影响执行效率
NSData * data = [NSData dataWithContentsOfURL:url];
NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSLog(@"%@",dict);
同步请求 2
NSURLRequest * request = [NSURLRequest requestWithURL:url];
NSError * error = nil;
NSURLResponse * response = nil;
NSData * data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
异步请求 1
NSURLRequest * request = [NSURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSLog(@"%@",dict);
}];
异步请求 2
NSURLRequest * request = [NSURLRequest requestWithURL:url];
NSURLConnection * connection = [NSURLConnection connectionWithRequest:request delegate:self];
异步请求 2 代理方法
_代理1____收到服务器响应
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSLog(@"收到响应");
}
_代理2____收到数据
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
NSLog(@"追加数据");
[_data appendData:data];
}
_代理3____数据传输完成
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:_data options:NSJSONReadingMutableContainers error:nil];
NSLog(@"%@",dict);
NSLog(@"完成加载,开始分析数据");
}
_代理4____数据传输错误
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(@"加载出错");
}
异步请求 3 —> GET请求
NSURLRequest * reuqest = [NSURLRequest requestWithURL:url];
NSURLSession * session = [NSURLSession sharedSession];
NSURLSessionDataTask * task = [session dataTaskWithRequest:reuqest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (!error) {
NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSLog(@"%@",dict);
}else
{
NSLog(@"%@",error);
}
}];
[task resume];
异步请求 4 —> POST请求
NSMutableURLRequest * request = [[NSMutableURLRequest alloc]initWithURL:url];
request.HTTPMethod = @"POST";
NSString * str = @"number=10&page=2";
request.HTTPBody = [str dataUsingEncoding:NSUTF8StringEncoding];
NSURLSession * section = [NSURLSession sharedSession];
NSURLSessionTask * task = [section dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSLog(@"%@",dict);
}];
[task resume];