如何使用AVPlayer进行基本身份验证从服务器播放视频文件?

时间:2016-07-25 12:06:50

标签: ios9 avplayer basic-authentication avplayerviewcontroller

我必须从服务器播放AVPlayer中的视频文件,但我还必须使用基本身份验证来播放此文件。这是我的代码

    NSMutableDictionary * headers = [NSMutableDictionary dictionary];
NSData *basicAuthCredentials = [[NSString stringWithFormat:@"username:password"] dataUsingEncoding:NSUTF8StringEncoding];
NSString *base64AuthCredentials = [basicAuthCredentials base64EncodedStringWithOptions:(NSDataBase64EncodingOptions)0];
[headers setValue:[NSString stringWithFormat:@"Basic %@", base64AuthCredentials] forKey:@"Authorization"];
NSURL *videoURL = [NSURL URLWithString:fileUrlString];
AVURLAsset * asset = [AVURLAsset URLAssetWithURL:videoURL options:headers];
AVPlayerItem * item = [AVPlayerItem playerItemWithAsset:asset];


AVPlayer *player = [AVPlayer playerWithPlayerItem:item];
AVPlayerViewController *playerViewController = [AVPlayerViewController new];
playerViewController.player = player;
playerViewController.delegate = (id)self;
[player play];
[self presentViewController:playerViewController animated:YES completion:nil];

3 个答案:

答案 0 :(得分:3)

@ ankit-jain你快到了。将HTTP标头添加到AVURLAsset的正确方法如下所示:

AVURLAsset * asset = [AVURLAsset URLAssetWithURL:videoURL options:@{@"AVURLAssetHTTPHeaderFieldsKey" : headers}];

当您这样做时,您的标题将与请求一起使用。 有关详细信息,请查看此答案:https://stackoverflow.com/a/23713028/1306884

答案 1 :(得分:0)

swift 3中没有

AVURLAssetHTTPHeaderFieldsKey。可以使用什么代替。不希望按照此处https://forums.developer.apple.com/thread/31646

的建议执行反向代理

https://github.com/kevinjameshunt/AVPlayer-HTTP-Headers-Example

答案 2 :(得分:0)

您应该使用URLCredentialStorage:

let credential = URLCredential(user: username, password: password, persistence: .forSession)
let protectionSpace = URLProtectionSpace(host: "my.host.com", port: 443, protocol: "https", realm: nil, authenticationMethod: NSURLAuthenticationMethodHTTPBasic)
URLCredentialStorage.shared.setDefaultCredential(credential, for: protectionSpace)
let player = AVPlayer(playerItem: AVPlayerItem(asset: AVURLAsset(url: url)))

在某些服务器上,视频的URL需要以http开头,尽管它是在https之后保护的。在这种情况下,您应该为URLProtectionSpace使用协议:“ https”,然后在URL中将“ https”更改为“ http”

重要:URL凭据:持久性:.forSession必须与AVURLAsset初始化位于同一线程。