swiftcurlnsurlrequesturlrequest

Swift - Convert URLRequest to cURL


How to convert URL Request to cURL? I know there are plugins available in Alamofire / Moya.

But I'm using native code.

Here is how I'm generating URLRequest.

var urlRequest = URLRequest(url: url) // URL is a param herel
var newHeaders: [String: String]
if let cookies = HTTPCookieStorage.shared.cookies {
  newHeaders = HTTPCookie.requestHeaderFields(with: cookies)
} else {
  newHeaders = [: ]
}
newHeaders = // add few more headers here
urlRequest.allHTTPHeaderFields = newHeaders
urlRequest.httpBody = data // set request body

How to log a cURL of above request?


Solution

  • You can simply try this URLRequest to cURL

    To use it in your code first import that extension and then simply call urlRequest.cURL() or urlRequest.cURL(pretty: true) to print pretty formatted curl.

    EDIT: Now the above gist has Alamofire support also