AVPlayer playing protected HLS, how to update token when it expires?

I am playing the protected HLS streams and the authorization token expires in 5 minutes,I am trying to achieve this with 'AVAssetResourceLoaderDelegate' and I'm getting an error 401 Unauthorized. The question is how to update the token inside asset? I've already tried to change it in resourceLoader loadingRequest.allHTTPHeaderFields but it is not working:

func resourceLoader(_ resourceLoader: AVAssetResourceLoader, shouldWaitForLoadingOfRequestedResource loadingRequest: AVAssetResourceLoadingRequest) -> Bool {

    func resourceLoader(_ resourceLoader: AVAssetResourceLoader, shouldWaitForLoadingOfRequestedResource loadingRequest: AVAssetResourceLoadingRequest) -> Bool {
        guard let url = loadingRequest.request.url else {
            loadingRequest.finishLoading(with: NSError(domain: "Invalid URL", code: -1, userInfo: nil))
            return false
        }
        
        // Create a URLRequest with the initial token
        var request = URLRequest(url: url)
        request.addValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
        request.allHTTPHeaderFields = loadingRequest.request.allHTTPHeaderFields
        // Perform the request
        let task = URLSession.shared.dataTask(with: request) { data, response, error in
            if let error = error {
                print("Error performing request: \(error.localizedDescription)")
                loadingRequest.finishLoading(with: error)
                return
            }
            
            guard let response = response as? HTTPURLResponse, response.statusCode == 200 else {
                let error = NSError(domain: "HTTP Error", code: (response as? HTTPURLResponse)?.statusCode ?? -1, userInfo: nil)
                print("HTTP Error: \(error.localizedDescription)")
                loadingRequest.finishLoading(with: error)
                return
            }
            
            if let data = data {
                loadingRequest.dataRequest?.respond(with: data)
            }
            loadingRequest.finishLoading()
        }
        
        task.resume()
        return true
    }
    
    return false

}

Hello @narendra1098. Your code is first adding an authorization token field to the request's headers:

request.addValue("Bearer \(token)", forHTTPHeaderField: "Authorization")

But after that it is overriding all the request's headers with:

request.allHTTPHeaderFields = loadingRequest.request.allHTTPHeaderFields

If you first set allHTTPHeaderFields, then add the token, are you able to authorize?

AVPlayer playing protected HLS, how to update token when it expires?
 
 
Q