5

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];
raed
  • 4,887
  • 4
  • 30
  • 49
ankit jain
  • 51
  • 1
  • 4

3 Answers3

6

@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

Community
  • 1
  • 1
Michael
  • 1,285
  • 18
  • 31
  • Why would anyone downvote this answer without leaving a comment, while it provides the proper solution to the problem? – Michael Dec 29 '16 at 13:36
  • this key is a private api. its not recommended to use in application. app can get rejected in appstore. – Mahesh Agrawal Dec 12 '19 at 08:06
0

AVURLAssetHTTPHeaderFieldsKey is not available in swift 3. What can be used instead. Do not want to do a reverse proxy as suggested here https://forums.developer.apple.com/thread/31646

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

Roopesh Mittal
  • 191
  • 2
  • 10
0

You should use the 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)))

On some Servers the url of the video need to start with: http although it is secured behind https. In that case you should use for URLProtectionSpace the protocol: "https" and in the url just change "https" to "http"

Important: URLCredential: persistence: .forSession needs to be at the same thread as the AVURLAsset initialization.