Question

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;
Was it helpful?

Solution

That delegate method, for iOS, is defined in NSURLConnectionDataDelegate and gives you the opportunity to control how the redirect is handled (you could cancel it, change it or return it unchanged).

In your case you want to let it request the URL as returned by the redirect response so a simple implementation would be:

- (NSURLRequest *)connection: (NSURLConnection *)inConnection
         willSendRequest: (NSURLRequest *)inRequest
        redirectResponse: (NSURLResponse *)inRedirectResponse {

    return inRequest;
}

I believe this should be the default behaviour though, so if the request isn't being processed, the problem is likely elsewhere...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top