Add custom header field in request of AVPlayer

Is it possible to send headers with an http request to an audio file when using AVPlayer? I need to be able to inspect the content of the header when received by the server in order to restrict access to the file being requested.


You can use AVURLAssetHTTPHeaderFieldsKey of AVURLAsset's init option to modify request headers.

For example:

NSMutableDictionary * headers = [NSMutableDictionary dictionary];
[headers setObject:@"Your UA" forKey:@"User-Agent"];
AVURLAsset * asset = [AVURLAsset URLAssetWithURL:URL options:@{@"AVURLAssetHTTPHeaderFieldsKey" : headers}];
AVPlayerItem * item = [AVPlayerItem playerItemWithAsset:asset];
self.player = [[AVPlayer alloc] initWithPlayerItem:item];

Note: I found this key in sources of WebKit, but this is a Private option key, So your app may reject by AppStore if you use this.


Answer in Swift, AVURLAssetHTTPHeaderFieldsKey option will work like a charm.

 let headers: [String: String] = [
    "custome_header": "custome value"
 ]
 let asset = AVURLAsset(url: URL, options: ["AVURLAssetHTTPHeaderFieldsKey": headers])
 let playerItem = AVPlayerItem(asset: asset)
 player = AVPlayer(playerItem: item)