· 1 min learn
On this Swift tutorial, I might like to provide you an instance about getting and parsing JSON knowledge utilizing URLSession and Codable protocol.
Dependencies
To start with only a few phrases about dependencies. From Swift 4 you don’t want any dependency to parse JSON knowledge, as a result of there are built-in protocols to deal with every little thing. In case you are nonetheless utilizing some form of Third-party it is best to positively ditch it for the sake of simplicity. By the way in which earlier than you add any exterior dependency into your challenge, please assume twice. 🤔
Networking
In case your activity is solely to load some form of JSON doc by means of HTTP from across the internet, – shock – you received’t want Alamofire in any respect. You should utilize the built-in URLSession class to make the request, and get again every little thing that you simply’ll want. The Basis networking stack is already a posh and really helpful stack, don’t make issues much more sophisticated with additional layers.
JSON parsing
Now, after the brief intro, let’s dive in and get some actual pretend JSON knowledge from the JSONPlaceholder internet service. I’m going to put the entire thing proper right here, you possibly can choose it, copy and paste right into a Swift playground file.
import Basis
import PlaygroundSupport
PlaygroundPage.present.needsIndefiniteExecution = true
struct Submit: Codable {
enum CodingKeys: String, CodingKey {
case id
case title
case physique
case userIdentifier = "userId"
}
let id: Int
let title: String
let physique: String
let userIdentifier: Int
}
let url = URL(string: "https://jsonplaceholder.typicode.com/posts")!
URLSession.shared.dataTask(with: url) { knowledge, response, error in
if let error = error {
print("Error: (error.localizedDescription)")
PlaygroundPage.present.finishExecution()
}
guard
let httpResponse = response as? HTTPURLResponse,
httpResponse.statusCode == 200
else {
print("Error: invalid HTTP response code")
PlaygroundPage.present.finishExecution()
}
guard let knowledge = knowledge else {
print("Error: lacking knowledge")
PlaygroundPage.present.finishExecution()
}
// be happy to uncomment this for debugging knowledge
// print(String(knowledge: knowledge, encoding: .utf8))
do {
let decoder = JSONDecoder()
let posts = strive decoder.decode([Post].self, from: knowledge)
print(posts.map { $0.title })
PlaygroundPage.present.finishExecution()
}
catch {
print("Error: (error.localizedDescription)")
PlaygroundPage.present.finishExecution()
}
}.resume()
As you possibly can see downloading and parsing JSON from the online is a very easy activity. This complete code snippet is round 50 traces of code. In fact it’s only a proof of idea, nevertheless it works and also you don’t want any dependency. It’s pure Swift and Basis.
To save some typing, you too can generate the ultimate objects straight from the JSON construction with these superb Xcode extensions.
The Codable
protocol – which is definitely a compound typealias
from Encodable & Decodable
protocols – makes the method of parsing JSON knowledge in Swift magical. 💫
Associated posts
· 2 min learn
Making a Swift framework should not be laborious. This tutorial will make it easier to making a common framework for complicated initiatives.
· 1 min learn
On this fast tutorial I am going to present you find out how to get all of the doable values for a Swift enum kind with a generic resolution written in Swift.
· 11 min learn
Be taught every little thing about Swift modules, libraries, packages, closed supply frameworks, command line instruments and extra.
· 6 min learn
Have you ever ever heard about Swift language attributes? On this article I am making an attempt to assemble all of the @ annotations and their meanings.