主线程中创建一个NSURLConnection并异步执行
[self performSelectorOnMainThread:@selector(start) withObject:nil waitUntilDone:YES]; - (void)start { //step 1:请求地址 NSURL *url = [NSURL URLWithString:@"www.2cto.com"]; //step 2:实例化一个request NSURLRequest *request =[NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0]; //step 3:创建链接 self.connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];//直接运行了 if (self.connection) { NSLog(@"链接成功"); }else { NSLog(@"链接失败"); } }
解决方法,修改代码为:
[self performSelectorOnMainThread:@selector(start) withObject:nil waitUntilDone:YES]; - (void)start { //step 1:请求地址 NSURL *url = [NSURL URLWithString:@"www.2cto.com"]; //step 2:实例化一个request NSURLRequest *request =[NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0]; //step 3:创建链接 self.connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO];//暂时不运行 [connection scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];//用NSRunLoopCommonModes [connection start]; if (self.connection) { NSLog(@"链接成功"); }else { NSLog(@"链接失败"); } }
原文地址:http://blog.csdn.net/fxmmc/article/details/40072843