Skip to content

Instantly share code, notes, and snippets.

@amfathi
Last active May 1, 2020 20:56
Show Gist options
  • Select an option

  • Save amfathi/ebe6cbeede3d8fa544422b407b0c9d8d to your computer and use it in GitHub Desktop.

Select an option

Save amfathi/ebe6cbeede3d8fa544422b407b0c9d8d to your computer and use it in GitHub Desktop.
Convert swift dictionary to JSON view. Helpful for copy-paste data from console to postman.
extension Dictionary {
func jsonView() -> String {
guard let data = try? JSONSerialization.data(withJSONObject: self, options: .prettyPrinted) else { return "" }
return String(data: data, encoding: .utf8) ?? ""
}
}
// MARK: - Network Logging
private func log(request: URLRequest, response: HTTPURLResponse?, data: Data?, error: Error?) {
print("=============================================")
print("URL:", request.url?.absoluteString ?? "")
print("Method:", request.httpMethod ?? "")
print("Headers:", request.allHTTPHeaderFields ?? "")
if let body = prettyString(request.httpBody) {
print("HTTP Body:", body)
}
print("Status:", response?.allHeaderFields["Status"] ?? "")
if let responseJSON = prettyString(data) {
print("Response:", responseJSON)
}
error.map { print("Error:", $0) }
print("=============================================")
}
private func prettyString(_ data: Data?) -> String? {
if let data = data,
let json = try? JSONSerialization.jsonObject(with: data, options: .allowFragments),
let prettyData = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted),
let jsonString = String(data: prettyData, encoding: .utf8) {
return jsonString
} else {
return nil
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment