Coding IOS + Swift
IOS + Swift Code: Read Data from Remote Json File
September 6, 2017
0
, ,

My JSON FILE:

{"teams":[{
    "id": "1",
    "clubName": "USJF",
    "isDeleted": "0"
  },
  {
    "id": "2",
    "clubName": "Docume",
    "isDeleted": "0"
  },
  {
    "id": 3,
    "clubName": "Chelsea",
    "isDeleted": 0
  },
  {
    "id": 4,
    "clubName": "Bercelona",
    "isDeleted": 0
}]}

JSON FILE Screenshot:

IOS CODE:

//
// ViewController.swift
// HelloJson
//
// Created by Arifur Rahman Zerin on 9/5/17.
// Copyright © 2017 ZERIN. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

@IBOutlet var labelTest: UILabel!
//the json file url
let URL_GET_TEAMS:String = “http://192.168.0.110/test/testjson.php”

//A string array to save all the names
var nameArray = [String]()

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
labelTest.text = “”;

getJsonFromUrl();

}
//this function is fetching the json from URL
func getJsonFromUrl(){

//created NSURL
let url = NSURL(string: URL_GET_TEAMS)

//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: “teams”)!)

//getting the avengers tag array from json and converting it to NSArray
if let heroeArray = jsonObj!.value(forKey: “teams”) 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: “clubName”) {

//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”;
print(name);
}
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}

}

WHEN YOU RUN, YOU WILL SEE THE DATA IN CONSOLE:

NEED TO SET LABEL PROPERTY SO THAT ALL VALUES GET ADDED:

IOS SIMULATOR OUTPUT:

About author

ZERIN

CodeIgniter: How To Call A Controller from another Controller

My JSON FILE: {"teams":[{ "id": "1", "clubName": "...

Read more

There are 0 comments

Leave a Reply

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