[IOS] a small example of NSURLConnection
Directly go to the code...
NSURLSession can be used after iOS7, but NSURLConnection is used for both iOS6 and iOS6.
@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
You can also directly use Block to send an asynchronous request:
[NSURLConnection sendAsynchronousRequest:theRequest queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) { NSLog(@"Finished"); }];