想要在 IOS 中取得某个 URL 的内容,或是使用像 PHP 中 CURL 的功能,在 IOS 里有个物件叫 NSURLConnection , NSURLConnection 提供了简单的 interface,让我们能够建立或取消一个网路连线, 也支援 delegate 的方式异步处理回应,另外还支援了 cache 管理机制,权限验证,cookie 等等。
简易的 Reuqest
一个 Request ,最简单的物件,就是要宣告一个 client 的物件,在 IOS 中, client 物件就是 NSMutableURLRequest,然后指定一个 URL 就能取得目标的内容,这里我宣告了以下两个变数,Url 设定成 Yahoo! 首页。
- 宣告 Url : NSString *url = @"https://tw.yahoo.com";
 - 宣告 Client : NSMutableURLRequest *requestClient
 
要将上述的 requestClient 传送 Request 的方式,是使用 NSURLConnection 这个 IOS 内建的物件,这里我设定参数 sendSynchronousRequest ,代表我要使用「系统同步」的方式取得网页内容,「系统同步」是最简单的 Request 方式,它会使程式依序执行,比较容易管理。
NSURLConnection 执行成功后,会回传一个 NSData 的资料格式,这个格式并非为纯文字,没办法直接使用他,所以我们要再将 NSData 转成 NSString 格式,并且要指定编码方式 encoding: NSUTF8StringEncoding。
Curl or Request 范例如下:
- NSString *url = @"https://tw.yahoo.com/";
 - NSMutableURLRequest *requestClient = [NSMutableURLRequest
 - requestWithURL:[NSURL URLWithString:url]
 - cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData
 - timeoutInterval:10
 - ];
 - [requestClient setHTTPMethod: @"GET"];
 - NSError *requestError;
 - NSURLResponse *urlResponse = nil;
 - //Make a request
 - NSData *response = [NSURLConnection
 - sendSynchronousRequest: requestClient
 - returningResponse: &urlResponse
 - error: &requestError
 - ];
 - NSString *responseData = [[NSString alloc]initWithData: response
 - encoding: NSUTF8StringEncoding
 - ];
 - NSLog(@"response = %@", responseData);
 
异步 Request
异步 Request 与 同步 Request 的差别就在於一个是会让程式整个停止,等待网路回应成功 ,而异步 Request 则不会卡住程式的运行。
想使用异步 Request , 要使用 NSURLConnection 的 sendAsynchronousRequest Method ,并且要宣告一个 Callback Function completionHandler。
范例如下:
- NSString *url = @"https://tw.yahoo.com/";
 - NSMutableURLRequest *requestClient = [NSMutableURLRequest
 - requestWithURL:[NSURL URLWithString:url]
 - cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData
 - timeoutInterval:10
 - ];
 - [requestClient setHTTPMethod: @"GET"];
 - NSOperationQueue *backgroundQueue = [[NSOperationQueue alloc] init];
 - [NSURLConnection sendAsynchronousRequest: requestClient
 - queue:backgroundQueue
 - completionHandler:^(NSURLResponse *response, NSData *data, NSError *error){
 - NSString *responseData = [[NSString alloc]initWithData: data
 - encoding: NSUTF8StringEncoding
 - ];
 - NSLog(@"Response = %@", responseData);
 - }
 - ];
 - NSLog(@"running");
 
上述的范例,执行后,萤幕会先印出 running ,然后等 Request 成功后,会再印出 tw.yahoo.com 的页面内容。