Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wilmarvh/06c1593e5c670f7c75554e2fc3caeb0a to your computer and use it in GitHub Desktop.
Save wilmarvh/06c1593e5c670f7c75554e2fc3caeb0a to your computer and use it in GitHub Desktop.
Ever wanted to generate cURL from URLRequest for faster debugging? Simply convert URLRequest in cURL format (Swift)
//
// ExtensionURLRequest.swift
//
// Created by Abhishek Maurya on 16/07/20.
// Copyright © 2020. All rights reserved.
//
import Foundation
extension URLRequest {
public func cURL(pretty: Bool = false) -> String {
let newLine = pretty ? "\\\n" : ""
let method = (pretty ? "--request " : "-X ") + "\(self.httpMethod ?? "GET") \(newLine)"
let url: String = (pretty ? "--url " : "") + "\'\(self.url?.absoluteString ?? "")\' \(newLine)"
var cURL = "curl "
var header = ""
var data: String = ""
if let httpHeaders = self.allHTTPHeaderFields, httpHeaders.keys.count > 0 {
for (key,value) in httpHeaders {
header += (pretty ? "--header " : "-H ") + "\'\(key): \(value)\' \(newLine)"
}
}
if let bodyData = self.httpBody, let bodyString = String(data: bodyData, encoding: .utf8) {
data = "--data '\(bodyString)'"
}
cURL += method + url + header + data
return cURL
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment