iOS中使用NSURLConnection处理HTTP同步与异步请求

2020-01-15 17:01:48刘景俊

        if ([data length] > 0 && connectionError == nil) { 
            NSString *documentsDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; 
            NSString *filePath = [documentsDir stringByAppendingPathComponent:@"apple.html"]; 
            [data writeToFile:filePath atomically:YES]; 
            NSLog(@"Successfully saved the file to %@",filePath); 
            NSString *html = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; 
            NSLog(@"HTML = %@",html); 
        }else if ([data length] == 0 && connectionError == nil){ 
            NSLog(@"Nothing was downloaded."); 
        }else if (connectionError != nil){ 
            NSLog(@"Error happened = %@",connectionError); 
        } 
    }]; 

2.通过NSURLConnection进行同步下载:
使用 NSURLConnection 的 sendSynchronousRequest:returningResponse:error:类方法,我们可以进行同步请求。在创建一个同步的网络连接的时候我们需要明白一点,并不是是我们的这个同步连接一定会堵塞我们的主线程,如果这个同步的连接是创建在主线程上的,那么这种情况下是会堵塞我们的主线程的,其他的情况下是不一定会堵塞我们的主线程的。如果你在 GCD 的全局并发队列上初始化了一个同步的连接,你其实并不会堵塞我们的主线程的。
我们来初始化第一个同步连接,并看看会发生什么。在实例中,我们将尝试获取 Yahoo!美国站点主页内容:

//synchronousRequest connection 
-(void)fetchYahooData{ 
    NSLog(@"We are here..."); 
    NSString *urlString = @"http://www.easck.com/>     NSURL *url = [NSURL URLWithString:urlString]; 
    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url]; 
    NSURLResponse *response = nil; 
    NSError *error = nil; 
    NSLog(@"Firing synchronous url connection..."); 
    NSData *data = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&error];