In this Swift JSON Tutorial we will learn about fetching and parsing JSON from a URL. You may already know what is JSON file. JSON stands for “JavaScript Object Notation” it is the most popular data interchange format. In our iOS Application we can use this to fetch data from an external MySQL Database. I have already posted a tutorial about Xcode JSON Example.
Update: Learn JSON Parsing using Swift 4.
So lets start this Swift JSON Tutorial.
Swift JSON Tutorial
The JSON File
- I already have my JSON file in my local xampp server. The file is as below.
- This is a very simple JSON file. As today we will learn only to fetch and display the names in our iOS Application. And in the next tutorial we will make the JSON filled with a little more data and we will learn creating a list with it.
Xcode Project
- So lets create a new Xcode Project. I am using Xcode 8.
- Again create a Single View Application, I have created SwiftJSONTutorial.
- In Main.storyboard drag a Label. And set Lines property of the Label to 0. Also Change the Width and Height of the Label so that it can easily hold all the names of the JSON.
- Also connect your Label to ViewController.swift, if you don’t know how to do this please go through the Xcode Button Tutorial, where I already explained about connecting a View to Code.
- Now come inside ViewController.swift and write the following code.
ViewController.swift
- Modify your ViewController.swift as below.
// // ViewController.swift // SwiftJSONTutorial // // Created by Belal Khan on 08/02/17. // Copyright © 2017 Belal Khan. All rights reserved. // import UIKit class ViewController: UIViewController { //the json file url let URL_HEROES = "http://192.168.1.105/json/heroes.php"; //A string array to save all the names var nameArray = [String]() //the label we create @IBOutlet weak var labelTest: UILabel! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. //calling the function that will fetch the json getJsonFromUrl(); } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //this function is fetching the json from URL func getJsonFromUrl(){ //creating a NSURL let url = NSURL(string: URL_HEROES) //fetching the data from the url URLSession.shared.dataTask(with: (url as? URL)!, completionHandler: {(data, response, error) -> Void in if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary { //printing the json in console print(jsonObj!.value(forKey: "avengers")!) //getting the avengers tag array from json and converting it to NSArray if let heroeArray = jsonObj!.value(forKey: "avengers") as? NSArray { //looping through all the elements for heroe in heroeArray{ //converting the element to a dictionary if let heroeDict = heroe as? NSDictionary { //getting the name from the dictionary if let name = heroeDict.value(forKey: "name") { //adding the name to the array self.nameArray.append((name as? String)!) } } } } OperationQueue.main.addOperation({ //calling another function after fetching the json //it will show the names to label self.showNames() }) } }).resume() } func showNames(){ //looing through all the elements of the array for name in nameArray{ //appending the names to label labelTest.text = labelTest.text! + name + "\n"; } } }
- Coding part is over the only thing we need to allow the http connection in the Info.plist file.
Modifying NSAppTransportSecurity
- Now click on Info.plist. And change it as shown in the image.
- As you can see I have added App Transport Security Settings. You can do it by clicking on the plus icon. And inside it you have to set Allow Arbitrary Loads as YES.
- Now thats it you can launch your application in Simulator.
- Bingo! Its working absolutely fine. If you are having problems you can get the source code of this Swift JSON Tutorial from below.
[sociallocker] Swift JSON Tutorial (1035 downloads) [/sociallocker]
So thats all for this Swift JSON Tutorial. In the next post we will make the JSON a little more filled with data and then we will see building a Custom Table View with Texts and Images.
And if you are having any problems or confusions regarding this Swift JSON Tutorial, don’t hesitate to leave your comments below. Thank You 🙂
Varsha Chauhan says
Hello sir…
I am making an android application in which i have completed the login and registration part using PHP and wamp server. Now i am stuck at point where i want that the logged in user should see the headings of the data in listview stored in database and when the user click on any of the item the next activity should open displaying full details of the heading. Also i want to filter the listview items on the basis of multiple conditions like in E-Commerce applications we can filter on the basis of brands,price,colour etc simultaneoulsy. I want that the listview items should be fetched from the database.
One more thing i want that the details of the item should contain a a hyperlink named “download” so that the image can be downloaded in the phone.
I want guidance on how to achieve them.
Please reply .
dt says
This is iOS (iPhone) NOT ANDROID so it won’t work. Sorry.
Ryan says
Will this work with AppleTV? I tried and debugged the URLsession and get a response but no data…
Response
Optional(HTTP/1.1 200 no error
Cache-Control: max-age=0, private, must-revalidate
Date: Fri, 20 Oct 2017 01:11:45 GMT
Content-Length: 0
Etag: W/”ad6542ff332466594ef909dd3d2f4153″
X-Request-Id: a7061f7d-f0a9-4468-8ba3-d63b1488f75d
X-Frame-Options: SAMEORIGIN
Content-Type: application/json; charset=utf-8
Connection: keep-alive
X-Content-Type-Options: nosniff
X-Xss-Protection: 1; mode=block
Transfer-Encoding: Identity
Via: 1.1 vegur
X-Runtime: 1.316226
Server: Cowboy)
data
Optional(4379 bytes)
json
nil
The code is…
URLSession.shared.dataTask(with: (url as? URL)!, completionHandler: {(data, response, error) -> Void in
print (“Response”)
print (response)
print (“data”)
print (data)
if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary {
print (“json”)
print (jsonObj)
any thoughts?
savita dayma says
thank u sir… its really helpful for me
David Collins says
Thanks, Belal. Very clear and concise.
valjo says
Hey Thanks for this amazing Tut.
Can you update the code with the new function of JSONDecoder().decode in Swift 4?
Would be a lot easier to see through.
Vivek Panchal says
How to Work with this type of JSON Data
{
“1”: {
“Name”: “Afghanistan”,
“Rate”: 0.435,
“PhoneNo”: “93”
},
“2”: {
“Name”: “Afghanistan”,
“Rate”: 0.6225,
“PhoneNo”: “9370, 9372, 9375, 9376, 9377, 9378, 9379”
},
“3”: {
“Name”: “Albania”,
“Rate”: 0.2775,
“PhoneNo”: “35543, 355422, 355423, 355424”
},
“4”: {
“Name”: “Albania”,
“Rate”: 0.3825,
“PhoneNo”: “3553, 3555, 3558, 35521, 35522, 35524, 35526, 35527, 35528, 35529, 35546, 35547, 35548, 35549, 35572”
}
}