Friday, August 25, 2017

Swift: Load JSON data from Web and Parse it

Download This Example Code Here.
 

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad()
    {
        super.viewDidLoad()

        //let url = URL(string: "http://api.fixer.io/latest")
        let url = URL(string: "http://arkayapps.com/sellapp/edumcq/service/getchapterbysubject.php?subjectid=42");
        
        let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in
            if error != nil
            {
                print ("ERROR")
            }
            else
            {
                if let content = data
                {
                    do
                    {
                        //Array
                        let myJson = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject
                        
                        print(myJson)
                            for index in 0...myJson.count-1 {
                                 let aObject = myJson[index] as! [String : AnyObject]
                                let chaptername = aObject["chaptername"] as! String
                                let chpid:Int? = Int(aObject["chapterid"] as! String)
                                let subid:Int? = Int(aObject["subjectid"] as! String)
                                
                                var chapter = Chapter(mark: chaptername, mycheptoriD: chpid!,mySubjectid: subid!)
                                print(chapter.chaptername)
                                print(chapter.chapterid)
                                print(chapter.subjectid)

                                
                        }
                        
                        
 
                    }
                    catch
                    {
                        
                    }
                }
            }
        }
        task.resume()
    
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    struct Chapter {
        var chaptername: String
        var chapterid: Int
        var subjectid: Int
        
        init(mark: String, mycheptoriD: Int, mySubjectid: Int) {
            self.chaptername = mark
            self.chapterid = mycheptoriD
            self.subjectid = mySubjectid
        }
        
    }


}

No comments:

Post a Comment