直接上代碼了。。。
在iOS7之後可以使用NSURLSession,但是考慮到兼顧iOS6還是使用NSURLConnection。
@interface ViewController()@property (nonatomic,strong) NSMutableData *receivedData; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; NSURLRequest *theRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.baidu.com"] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0]; NSURLConnection *theConncetion=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self]; if (theConncetion) { _receivedData = [NSMutableData data]; } } -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { [_receivedData appendData:data]; NSLog(@"Downloading..."); } -(void)connectionDidFinishLoading:(NSURLConnection *)connection { NSLog(@"Finished"); } @end
也可以直接用Block發個異步請求:
[NSURLConnection sendAsynchronousRequest:theRequest queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) { NSLog(@"Finished"); }];