Last active
May 1, 2020 20:56
-
-
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.
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
| extension Dictionary { | |
| func jsonView() -> String { | |
| guard let data = try? JSONSerialization.data(withJSONObject: self, options: .prettyPrinted) else { return "" } | |
| return String(data: data, encoding: .utf8) ?? "" | |
| } | |
| } |
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
| // 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