I am using NSURLConection and its delegate methods to asynchronously get data from an online TTS api. Here is the URL I am trying to load:
http://tts-api.com/tts.mp3?q=hello world
The above URL redirects and give us an MP3 file which I need to download. I have used the following delegate method to download the mp3 file:
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
if (connection == connectionToTTSAPI) {
mp3Manager = [NSFileManager defaultManager];
localPath = [[[NSBundle mainBundle] resourcePath]stringByAppendingPathComponent:@"hello.mp3"];
mp3Handler = [NSFileHandle fileHandleForWritingAtPath:localPath];
if (!mp3Handler) {
[[NSFileManager defaultManager] createFileAtPath:localPath contents:nil attributes:nil];
mp3Handler = [NSFileHandle fileHandleForWritingAtPath:localPath];
}
@try {
[mp3Handler seekToEndOfFile];
[mp3Handler writeData:data];
}
}
}
Since there are more than one NSURLConnection I am using in my program I have set an if condition to recognise the response is for which connection. But I was not getting the mp3 file, so I set a break point inside the delegate method and discovered that the the connection to TTS API is never getting a response. I think it is because of the redirection. I have seen the use of the following method when i went through some other questions, but I didn't find such a function in NSURLConnectionDelegate
, and also as a starter with NSURLConnection I don't know how to use the method for handling redirects. None of the results gave me the clear idea how to use it.
- (NSURLRequest *)connection: (NSURLConnection *)inConnection
willSendRequest: (NSURLRequest *)inRequest
redirectResponse: (NSURLResponse *)inRedirectResponse;