-
-
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)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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