MediaPlayer.framework (MPMoviePlayerController) воспроизводит фильм с URL-адреса, который требует прав доступа
У меня проблемы с воспроизведением фильма с URL, который имеет базовую http аутентификацию.
Вот код:
NSURLCredential *credential = [[NSURLCredential alloc]
initWithUser:@"user"
password:@"password"
persistence:NSURLCredentialPersistenceForSession];
NSURLProtectionSpace *protectionSpace = [[NSURLProtectionSpace alloc]
initWithHost:@"moze.dyndns.org"
port:80
protocol:@"http"
realm:nil
authenticationMethod:NSURLAuthenticationMethodHTTPBasic];
[[NSURLCredentialStorage sharedCredentialStorage] setDefaultCredential:credential forProtectionSpace:protectionSpace];
NSURL *videoURL = [NSURL URLWithString:@"http://moze.dyndns.org/test/test.mov"];
moviePlayerController = [[MPMoviePlayerViewController alloc] initWithContentURL:videoURL];
[moviePlayerController.view setFrame:self.view.bounds];
[self.view addSubview:moviePlayerController.view];
MPMoviePlayerController *mp = [moviePlayerController moviePlayer];
mp.controlStyle = MPMovieControlStyleDefault;
[mp prepareToPlay];
[[moviePlayerController moviePlayer] play];
Я получаю сообщение об ошибке "Операция не может быть завершена. (MediaPlayerErrorDomain error -1013.)", ErrorLog в NULL, также как accessLog.
Я использую сервер Apache с AuthType Basic, учетные данные верны, проверил их в веб-браузере. Нет проблем с воспроизведением, если аутентификация отключена.
Пожалуйста, помогите, я не могу найти, что не так.
1 ответ
Я не мог получить MPMoviePlayerController
чтобы сделать проверку подлинности должным образом, даже думал, что документы Apple говорят иначе. ОЧЕНЬ хакерское решение, которое я придумал, состояло в том, чтобы использовать Apple CustomHTTPProtocol
перехватить ответ и предоставить ответ на запрос аутентификации. Я полагаю, что первоначальной целью этого протокола была обработка аутентификации для UIWebViews
,
Ссылка на CustomHTTPProtocol
: https://developer.apple.com/library/ios/samplecode/CustomHTTPProtocol/Listings/Read_Me_About_CustomHTTPProtocol_txt.html
Моя декларация интерфейса:
@interface SampleViewController() <CustomHTTPProtocolDelegate>
Создание MPMoviePlayerController
в моем SampleViewController
:
NSString *fullURLString = @"http://www.samplesite.com/samplemovie.mp4";
NSURL *fullURL = [NSURL URLWithString:fullURLString];
[CustomHTTPProtocol setDelegate:self];
[CustomHTTPProtocol start];
NSURLCredential *credential = [[NSURLCredential alloc]
initWithUser:@"username"
password:@"password"
persistence:NSURLCredentialPersistenceForSession];
NSURLProtectionSpace *protectionSpace = [[NSURLProtectionSpace alloc]
initWithHost:fullURL.host
port:80
protocol:fullURL.scheme
realm:@"your-realm"
authenticationMethod:NSURLAuthenticationMethodDefault];
[[NSURLCredentialStorage sharedCredentialStorage] setDefaultCredential:credential forProtectionSpace:protectionSpace];
self.moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:fullURL];
[self.moviePlayer prepareToPlay];
[self.moviePlayer setShouldAutoplay:NO];
[self.moviePlayer setControlStyle:MPMovieControlStyleEmbedded];
[self.moviePlayer.view setFrame:self.sampleView.bounds];
[self.moviePlayer.backgroundView setBackgroundColor:[UIColor colorWithWhite:0.9 alpha:1.0]];
[self.moviePlayer.view setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight];
[self.sampleView addSubview:self.moviePlayer.view];
Также в моем SampleViewController
У меня есть пара методов делегата. Для базовой аутентификации это довольно просто:
- (BOOL)customHTTPProtocol:(CustomHTTPProtocol *)protocol canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace
{
BOOL canAuth = ([[protectionSpace authenticationMethod] isEqual:NSURLAuthenticationMethodHTTPBasic] &&
[[protectionSpace realm] isEqualToString:@"your-realm"]);
return canAuth;
}
- (void)customHTTPProtocol:(CustomHTTPProtocol *)protocol didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
NSURLCredential *newCredential = [NSURLCredential credentialWithUser:@"username"
password:@"password"
persistence:NSURLCredentialPersistenceForSession];
[[challenge sender] useCredential:newCredential forAuthenticationChallenge:challenge];
}
После звонка start
все запросы http и https проходят через CustomHTTPProtocol
модуль
Я не включил CustomHTTPProtocol
так как Apple предоставляет источник, и это действительно долго. Я внес некоторые изменения, чтобы он работал с ARC, но в основном это тот же код.
Надеюсь, это работает для вас.