URL请求一般分为同步和异步两种,请求是需要耗时的,所以肯定不能放在主线程中进行,这样会阻塞UI,这两种请求方式都可以在其他线程使用
1、同步方式
通过GCD来放到其他线程中执行
dispatch_queue_t dispatchQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); dispatch_async(dispatchQueue, ^(void) { NSURL *url = [NSURL URLWithString:urlAsString]; NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url]; NSURLResponse *response = nil; NSError *error = nil; NSData *data = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&error]; if ([data length] > 0 && error == nil) { //处理data } else if ([data length] == 0 && error == nil) { //数据为空 } else if (error != nil) { //请求出错 } });
2、异步方式
通过方法
NSURLConnection的方法
+ (void)sendAsynchronousRequest:(NSURLRequest *
)request
queue:(NSOperationQueue *
)queue
completionHandler:(void (^)(NSURLResponse*, NSData*, NSError*)
)handler
NSURL *url = [NSURL URLWithString:urlString]; NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:5]; [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error){ if ([data length] >0 && error == nil) { [self saveData:data]; } else if ([data length] == 0 && error == nil) { //获取数据为空,报错 } else if (error != nil) { NSLog(@"Error happened : %@",error.localizedDescription); } }];