Press ESC to close

Swift Taking Json Data

Json data are of the major types in every project. When taking data from a service, we shoot it json. That is why every single Json has a large prefix of data. In our previous writings, we saw how to draw data with C #. In this article I will talk about how to get Json data with Swift. In fact, there are a lot of resources on the internet. Although there are not many sources in Turkish, there are many ways to extract English Json data. These roads are often much longer. Youtube’da Kerim Caglar has a nice video that is told. You can also get it here. I write blogs for myself and for those who are not available to watch videos.

First we need to determine the URL to which we will pull the Json data. This Url is important to us. Let’s check the accuracy and work. I will draw this data here so that you can be an example and you can use it comfortably. We need to convert this Url to Url type. The next thing we need to look at is whether the URL is http or https. Because http is insecure and you need to set the permissions in the info.plist file for this. This will be allowed in App Transport Security Settings. Once we have made these adjustments, we can take data. we define a variable as the incoming data. We then use the variable Data function to set the data in the Url that we have exported. Then we create a variable of type JsonDecoder to insert json data into a model.

let url = URL(string:"https://jsonplaceholder.typicode.com/posts")!
let gelenData = try! Data(contentsOf:url)
var jsonDecoder = JSONDecoder()

Up to here, our operations were very simple. Now we need to get the data into a model. We must create a class for this. I come up on my project and create a swift file from the Data name. After that, we need to create a structure in the form of the file that comes in this file. When we look at the future data, we see that there are 4, and that the integer of the two is the string type. According to these, we are building a structure. Make sure to do this for the Codable protocol.

import Foundation
struct Veriler:Codable {
    var userId:Int
    var id:Int
    var title:String
    var body:String 
    
}

Now we convert the structure to JsonDecoder which we have created. As the last operation, we print the first of these data.

let veriler = try? jsonDecoder.decode([Veriler].self, from: gelenData)
        
        dump(veriler?.first)

This is what you see as you see below.

If you have any questions, you can contact me by email or comment.

Leave a Reply

Your email address will not be published. Required fields are marked *