logo
TOOLS TO HELP YOU LEARN
teachers, students, everyone
Tools | Blog | Account | Learn
Login Status

JSONSerialization Swift 3
How to Parse JSON Data from Web to use in your App
Jan 17, 2017

Create a new single view project and copy the code below into your ViewController.swift (see full code at bottom of this page)


The var json:[String:AnyObject] = [:]; is used to store the JSON data

We have stored a JSON file on the Learnedu.US web servers. We point to it here: (see it on the server here)

let urlString = "http://learnedu.us/learn/tuts/json.php"

We use that in the getJSON method (see below):

let url = URL(string: urlString)

URLSession.shared.dataTask(with:url!) { (data, response, error) in

The URLSession connects to the json.php page and pulls the data down.

The JSONSerialization object deciphers the data into a more manageable format

self.json = try JSONSerialization.jsonObject(with: data!, options:.allowFragments) as! [String:AnyObject]

You can then treat the data as a dictionary array as we do below:

let myData = self.json["data"]! //save everything to myData

let meCount = Int(self.json["data"]!.count) - 1;//get number to use for our loop

for index in 0...meCount {

let myLine = myData[index] as! [String:Any];//break down particular line and display to screen

print(myLine["name"]!)

print(myLine["president_num"]!)

print(myLine["img"]!)

}

That's all there is to decoding the JSON data. The rest of the code deals with looking the URL that was provided in the JSON data and displaying an image based on that URL. I provide this as an example of how you can JSON in a real application.

Otherwise, you're ready to run the code. (see full code below). Enjoy!

  •                   
      import UIKit
    
    class ViewController: UIViewController {
        
        var json:[String:AnyObject] = [:];
        
        var playButton:UIButton?
        var myImage:UIImageView?
     
    
        override func viewDidLoad() {
            super.viewDidLoad()
          //  callFileFromWeb()
            getJSON();
            
            myImage = UIImageView(frame: CGRect(x:0, y:0, width:200, height:200))
            myImage?.center = self.view.center
            
            // Do any additional setup after loading the view, typically from a nib.
            playButton = UIButton(type: UIButtonType.system) as UIButton
            playButton!.frame = CGRect(x: 25, y: 60, width: 110, height: 35)
            playButton!.backgroundColor = UIColor.lightGray
            playButton!.setTitle("Show Image", for: UIControlState.normal)
            // playButton!.setImage(UIImage(named: "play.png"), for: UIControlState.normal)
            playButton!.tintColor = UIColor.black
            playButton!.addTarget(self, action: #selector(ViewController.playButtonTapped(_:)), for: .touchUpInside)
            self.view.addSubview(playButton!)
        }
        
        func playButtonTapped(_ sender:UIButton)
        {
             nextDownload()
        }
        
        
        
        let urlString = "http://learnedu.us/learn/tuts/json.php"
        
        func getJSON(){
        
        let url = URL(string: urlString)
        URLSession.shared.dataTask(with:url!) { (data, response, error) in
        if error != nil {
            print("There was an issue");
        print(error)
        } else {
        do {
        print("JSON WORK******************");
        self.json = try JSONSerialization.jsonObject(with: data!, options:.allowFragments) as! [String:AnyObject]
    
       
           let myData = self.json["data"]! //save everything to myData
            
            let meCount = Int(self.json["data"]!.count) - 1;//get number to use for our loop
            
            for index in 0...meCount {
           
                let myLine = myData[index] as! [String:Any];//break down particular line and display to screen
                print(myLine["name"]!)
                print(myLine["president_num"]!)
                print(myLine["img"]!)
            
            }
            
          
      
        } catch let error as NSError {
        print(error)
        }
        }
        
        }.resume()
        
        
        }
        
        
        
        
        
        
        
        func nextDownload(){
             let meCount = Int(self.json["data"]!.count) - 1;
            let randomNum = arc4random_uniform(UInt32(meCount))
            print(randomNum)
            let myData = self.json["data"]!
            let myLine = myData[Int(randomNum)] as! [String:Any];//break down particular line and display to screen
            
            let imageUrlString = myLine["img"]!
            let imageUrl:URL = URL(string: imageUrlString as! String)!
            
            // Start background thread so that image loading does not make app unresponsive
            DispatchQueue.global(qos: .userInitiated).async {
                
                let imageData:NSData = NSData(contentsOf: imageUrl)!
                
                // When from background thread, UI needs to be updated on main_queue
                DispatchQueue.main.async {
                    let image = UIImage(data: imageData as Data)
                   
                    self.myImage?.image = image
                    self.myImage?.contentMode = UIViewContentMode.scaleAspectFit
                    self.view.addSubview(self.myImage!)
                }
            }
        }
        
        
        }
                      
                      

    Comments:




    No comments posted

  • blog

    Past Posts

    Dropbox Public Folder Alternative
    Jun 4, 2017

    Getting Started with NodeJS
    May 1, 2017

    Scratch Intro: Racing Game
    Jan 15, 2017

    Five Best Educational Tools For Teachers
    Feb 3, 2017

    Coding Gravity
    Feb 22, 2017

    Drones in Eduction
    March 2, 2017

    Javascript Intro
    April 1, 2017

    iPhone Streaming Audio App
    April 15, 2017

    Installing MySQL
    May 15, 2017

     

     


     

    Thank You!