1. 程式人生 > 其它 >Alamofire4.x開原始碼分析(四)Timeline和cURL Command Output

Alamofire4.x開原始碼分析(四)Timeline和cURL Command Output

2019獨角獸企業重金招聘Python工程師標準>>> hot3.png

Timeline(時間統計)

Timeline是Alamofire提供的貫穿整個request生命週期的時間統計方案,可以通過response.timeline來訪問.

Alamofire.request("https://httpbin.org/get").responseJSON { response in
    print(response.timeline)
}

如下列印

Timeline: 
    { 
    "Latency": 1.474 secs, //請求到伺服器響應
    "Request Duration": 1.478 secs,//請求開始到完成
    "Serialization Duration": 0.013 secs,//序列化時間
    "Total Duration": 1.491 secs //總時間
      }

URL Session Task Metrics

在iOS10中,蘋果提供了URLSessionTaskMetrics的API,和timeline非常相似,它支援更多的統計資料,並支援任何型別的響應.

Alamofire.request("https://httpbin.org/get").responseJSON { response in
    //版本限定
    if #available(iOS 10.0, *) {
        print(response.metrics)
    }
}
Request) <NSURLRequest: 0x60000001f9a0> { URL: https://httpbin.org/get }
(Response) <NSHTTPURLResponse: 0x600000223f60> { URL: https://httpbin.org/get } { status code: 200, headers {
    "Access-Control-Allow-Credentials" = true;
    "Access-Control-Allow-Origin" = "*";
    Connection = "keep-alive";
    "Content-Length" = 375;
    "Content-Type" = "application/json";
    Date = "Tue, 04 Jul 2017 00:43:51 GMT";
    Server = "meinheld/0.6.1";
    Via = "1.1 vegur";
    "X-Powered-By" = Flask;
    "X-Processed-Time" = "0.00100803375244";
} }
(Fetch Start) 2017-07-04 00:43:54 +0000
(Domain Lookup Start) 2017-07-04 00:43:54 +0000
(Domain Lookup End) 2017-07-04 00:43:54 +0000
(Connect Start) 2017-07-04 00:43:54 +0000
(Secure Connection Start) 2017-07-04 00:43:55 +0000
(Secure Connection End) 2017-07-04 00:43:55 +0000
(Connect End) 2017-07-04 00:43:55 +0000
(Request Start) 2017-07-04 00:43:55 +0000
(Request End) 2017-07-04 00:43:55 +0000
(Response Start) 2017-07-04 00:43:55 +0000
(Response End) 2017-07-04 00:43:55 +0000
(Protocol Name) http/1.1
(Proxy Connection) NO
(Reused Connection) NO
(Fetch Type) Network Load

cURL Command Output(輸出請求url)

開發過程中我們都有自己拼接引數到url的經歷,幸運的是Alamofire實現除錯過程中直接輸出請求url和引數,方便了我們在xcode以外做介面除錯,比如瀏覽器,postman等工具.

let request = Alamofire.request("https://httpbin.org/get", parameters: ["foo": "bar"])
debugPrint(request)

輸出

$ curl -i \
    -H "User-Agent: Alamofire/4.0.0" \
    -H "Accept-Encoding: gzip;q=1.0, compress;q=0.5" \
    -H "Accept-Language: en;q=1.0,fr;q=0.9,de;q=0.8,zh-Hans;q=0.7,zh-Hant;q=0.6,ja;q=0.5" \
    "https://httpbin.org/get?foo=bar"

轉載於:https://my.oschina.net/roycehe/blog/1153853