HTTPでURL先の中身を取得する(2)
丁寧に書く場合は以下の方法もある。
URLを取得するコントローラーとかで
NSURL *url = [NSURL URLWithString:urlString];
// リクエストを作成
NSURLRequest *req = [ NSURLRequest requestWithURL : url
cachePolicy: NSURLRequestUseProtocolCachePolicy
timeoutInterval: 30 ];
NSURLConnection *connection=[[NSURLConnection alloc] initWithRequest:req delegate:self];
if (connection) {
// Create the NSMutableData that will hold
// the received data
receivedData=[[NSMutableData data] retain];
} else {
// inform the user that the download could not be made
}
とやり、あとは、下記のdelegateを呼ぶだけでOK。
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[receivedData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[receivedData appendData:data];
}
- (void)connection:(NSURLConnection *)connection
didFailWithError:(NSError *)error
{
// release the connection, and the data object
[connection release];
[receivedData release];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
// 受信完了 receivedData
}