Last active
August 29, 2022 15:40
-
-
Save peterprokop/16790dfa1320211b20c94a3f4dd95464 to your computer and use it in GitHub Desktop.
Print NSURLRequest in cURL format (Swift 3)
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
// | |
// URLRequest.swift | |
// | |
// Created by Peter Prokop on 17/08/2017. | |
import Foundation | |
public extension URLRequest { | |
/// Returns a cURL command for a request | |
/// - return A String object that contains cURL command or "" if an URL is not properly initalized. | |
public var cURL: String { | |
guard | |
let url = url, | |
let httpMethod = httpMethod, | |
url.absoluteString.utf8.count > 0 | |
else { | |
return "" | |
} | |
var curlCommand = "curl --verbose \\\n" | |
// URL | |
curlCommand = curlCommand.appendingFormat(" '%@' \\\n", url.absoluteString) | |
// Method if different from GET | |
if "GET" != httpMethod { | |
curlCommand = curlCommand.appendingFormat(" -X %@ \\\n", httpMethod) | |
} | |
// Headers | |
let allHeadersFields = allHTTPHeaderFields! | |
let allHeadersKeys = Array(allHeadersFields.keys) | |
let sortedHeadersKeys = allHeadersKeys.sorted(by: <) | |
for key in sortedHeadersKeys { | |
curlCommand = curlCommand.appendingFormat(" -H '%@: %@' \\\n", key, self.value(forHTTPHeaderField: key)!) | |
} | |
// HTTP body | |
if let httpBody = httpBody, httpBody.count > 0 { | |
let httpBodyString = String(data: httpBody, encoding: String.Encoding.utf8)! | |
let escapedHttpBody = URLRequest.escapeAllSingleQuotes(httpBodyString) | |
curlCommand = curlCommand.appendingFormat(" --data '%@' \\\n", escapedHttpBody) | |
} | |
return curlCommand | |
} | |
/// Escapes all single quotes for shell from a given string. | |
static func escapeAllSingleQuotes(_ value: String) -> String { | |
return value.replacingOccurrences(of: "'", with: "'\\''") | |
} | |
} |
I guess this will work more easily
https://gist.github.com/abhi21git/3dc611aab9e1cf5e5343ba4b58573596
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Though a quick Suggestion :
.....
let allHeadersFields = allHTTPHeaderFields ?? ["":""]
-- Line 33.....
curlCommand = curlCommand.appendingFormat(" -H '%@: %@' \\\n", key, self.value(forHTTPHeaderField: key) ?? "")
-- Line 37.....
Using Null Coalescing Operator, coz force unwrap crashes sometimes. =)