the easiest way is to use sendSynchronousRequest:returningResponse:error: from NSURLConnection.
__autoreleasing NSError *error = nil;
__autoreleasing NSURLResponse *response = nil;
NSData *responseData = [NSURLConnection sendSynchronousRequest:_request returningResponse:&response error:&error];
[responseData writeToFile:savePath atomically:YES];
Assume savePath
is a NSString contains a valid path.
if you want to use connectionWithRequest:delegate: as mentioned in your code, you will have to implement the following delegate methods:
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(@"Error: %d %@", [error code], [error localizedDescription]);
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
responseData = [NSMutableData data];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[responseData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[responseData writeToFile:savePath atomically:YES];
}
here responseData is an instance variable declared with:
NSMutableData *responseData;
and your class must conforms the NSURLConnectionDataDelegate
and NSURLConnectionDelegate
protocols.