How to detect if the request was served via http/1.1 or http2.0

We would like to make a distinction as to which request was served via HTTP/2 or HTTP/1.1

I looked HTTPURLResponse api and other api's in CFNetwork to see if we can determine this.

I have however not been succesfull in finding if the specific API is served as http/1.1 or http/2


Is there a API call I'm missing that would give this information?


Thank you,

Sohil

Answered by TheCD in 326628022

You can use URLSessionTaskTransactionMetrics.networkProtocolName to get this information. Example:


    override func viewDidLoad() {
        super.viewDidLoad()
        session.dataTask(with: URL(string: "https://api.music.apple.com/")!) { _, _, _ in }.resume()
    }

    func urlSession(_ session: URLSession, task: URLSessionTask, didFinishCollecting metrics: URLSessionTaskMetrics) {
        let transctionMetrics = metrics.transactionMetrics
        for metric in transctionMetrics {
            print("\(metric.request.url!)")
            print("\(metric.networkProtocolName ?? "nil")")
        }
    }


Output:


https://api.music.apple.com/
h2
https://developer.apple.com/musickit/
nil
https://developer.apple.com/musickit/
http/1.1
Accepted Answer

You can use URLSessionTaskTransactionMetrics.networkProtocolName to get this information. Example:


    override func viewDidLoad() {
        super.viewDidLoad()
        session.dataTask(with: URL(string: "https://api.music.apple.com/")!) { _, _, _ in }.resume()
    }

    func urlSession(_ session: URLSession, task: URLSessionTask, didFinishCollecting metrics: URLSessionTaskMetrics) {
        let transctionMetrics = metrics.transactionMetrics
        for metric in transctionMetrics {
            print("\(metric.request.url!)")
            print("\(metric.networkProtocolName ?? "nil")")
        }
    }


Output:


https://api.music.apple.com/
h2
https://developer.apple.com/musickit/
nil
https://developer.apple.com/musickit/
http/1.1
How to detect if the request was served via http/1.1 or http2.0
 
 
Q