Thursday, August 13, 2009

Handling redirects with initWithContentURL

I keep running into this problem so I thought that I should post my solution. There are some classes in the iPhone SDK like the MPMoviePlayerController that have an initWithContentURL method. However, the problem is that the URL I have is one that may issue a redirect response when requested. When I provide such a URL to initWithContentURL the player tells me that it cannot play me file. To work around this problem I wrote some very simple code.

The first thing you need to do is to build a HEAD request using NSMutableURLRequest. Then create an NSURLConnection settings the delegate as the current instance.

NSMutableURLRequest *headRequest =
[NSMutableURLRequest requestWithURL:resourceURL
cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];

[headRequest setHTTPMethod:@"HEAD"];

connection = [[NSURLConnection alloc]
initWithRequest:headRequest delegate:self];

Now we just need to implement the delegate method to play the URL from the response.

- (void)connection:(NSURLConnection *)connection
didReceiveResponse:(NSURLResponse *)response {

// Now we have resolved the URL so play the movie
thePlayer = [[MPMoviePlayerController alloc]
initWithContentURL:[response URL]];

[thePlayer play];

Obviously, this example handles one redirect but you can see that you can easily have it loop and until [response statusCode] == 200.


  1. Занятно пишете, жизненно. Все-таки, для того, чтобы делать по-настоящему интересный блог, нужно не едва сообщать о чем-то, но и делать это в интересной форме

  2. оригинальная идея. Интересно сколько времени он на это потратил

  3. Шрифт тяжкий читается у вас на блоге