Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to user Basic Authentication with AVPlayer to play video file from server?

I have to play a video file in AVPlayer from server but i also have to use basic authentication to play this file.here is my code

    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];
like image 568
ankit jain Avatar asked Jul 25 '16 12:07

ankit jain


1 Answers

@ankit-jain you're almost there. The correct way to add HTTP headers to the AVURLAsset looks like this:

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

When you do it that way, your headers are used along with the request. Have a look at this answer for more details: https://stackoverflow.com/a/23713028/1306884

like image 196
Michael Avatar answered Nov 05 '22 00:11

Michael