iOS Mediaplayer and URL redirection

2019-08-19 12:10发布

问题:

I'm trying to implement a MPMedia player to play internet files. So far I have managed to open the media player with links to videos hosted by me. The problem starts when I try to load an url that doesn't directly map to a file but instead gets redirected to the file.

The initial url looks like this: h*tp://www.example.com/numbers/numbers/numbers

and when I put it in my browser it is automatically changed for something like this: h*tp://www.example.com/numbers.mp4?to=numbers

When I use the initial url directly, just like I was doing with direct urls, the player comes up and inmediatly goes down without playing the video.

I have tried NSURLConnection to get the redirect url but I haven´t been able to get it working, somehow the method - connection:willSendRequest:redirectResponse: doesn't get called. I think it may be because it has been removed in iOS 5, but I don't know any alternatives, and this kind of problems are really undocumented.

Here is my code: (I've skipped the shortUrl initialization, it works).

NSLog(@"%@",shortUrl);

redirecionando=TRUE;

NSURLConnection * conection = [[NSURLConnection alloc]initWithRequest:[NSURLRequest requestWithURL:shortUrl] delegate:self];
[conection start];

while(self.redirecting);

self.moviePlayerController = [[MPMoviePlayerViewController alloc] initWithContentURL:finalurl];
moviePlayerController.view.frame = self.view.bounds;
[self presentMoviePlayerViewControllerAnimated:moviePlayerController];
moviePlayerController.moviePlayer.controlStyle = MPMovieControlStyleFullscreen;
moviePlayerController.moviePlayer.shouldAutoplay = YES;
[moviePlayerController.moviePlayer prepareToPlay];
moviePlayerController.moviePlayer.fullscreen=YES;



}

- (NSURLRequest *)connection: (NSURLConnection *)inConnection
             willSendRequest: (NSURLRequest *)inRequest
            redirectResponse: (NSURLResponse *)inRedirectResponse;
{
    finalurl=inRequest.URL; 
    self.redirecting=FALSE;
    return inRequest;
}

I know that this last methos isn't getting called, I NSLogged it. Right now, when the above code gets executed it just waits because of the while loop.

By the way, I cannot use an external api to discover the redirection like http://longurl.org/ because the link returns a token access for the device that asks for it.

Thanks in advance.

回答1:

I solved it. It turs out that with the line:

while(self.redirecting);

I was bloking the main thread and thus preventing the method connection: willSendRequest: redirectResponse: from being called. I've solved it getting the code below that line and putting it into another function called from the redirect method. I've also had to modify the redirect method because it got called many times, even with the original url before arriving at the mp4.

Thanks if you took the time to read the question.