Pretty printing JSON response in Debug View (Xcode)
Don’t know about you devs but I like my network responses pretty printed. This is because I’m picky about these things and also it helps me debug if my application behaves not the way i intended to.
What we’re trying to achieve:
Let’s dive into it.
When we make a network request using URLSession, we get Data from server response. So let’s create extensions of Data and Dictionary.
Now in your APIService class (from where you perform network requests), print the obtained response as: (line no. 18)
What we’ve done is:
- First we converted the Data obtained from server to NSDictionary.
- Then, we converted the NSDictionary to [String: Any]. (Using Data + Extensions.swift)
- Finally, we pretty printed the above value using Dictionary + Extensions.swift.
This is all. Now you’ve got a logger that prints all your GET and POST requests. Happy Coding!
Check out my other article:
https://medium.com/@nabs107/using-generics-to-handle-get-and-post-requests-swift-3cd8a9285293