//
// ViewController.m
// NSURLConnection
//
// Created by zmx on 16/1/26.
// Copyright © 2016年 zmx. All rights reserved.
//
#import "ViewController.h"
@interface ViewController () <NSURLConnectionDataDelegate>
@property (nonatomic, strong) NSURLConnection *connection;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
//同步请求,主线程会被阻塞,直到服务器返回数据
// [self sync];
//异步请求,主线程不会被阻塞,服务器返回数据时会调用代理方法
[self async];
}
- (void)sync {
NSData *data = [NSURLConnection sendSynchronousRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.baidu.com"]] returningResponse:nil error:nil];
NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"%@", str);
}
- (void)async {
self.connection = [[NSURLConnection alloc] initWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.baidu.com"]] delegate:self];
[self.connection start];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"%@", str);
}
@end