Tuesday, 19 December 2017

Call API using JSON Serialization

step 1: Drag and drop UITableview Controller on ViewController.
step 2: Create Tableviewcell cocoatouch file with xib.
step 3: In .xib file, put UIImageview and Label. (Depends on API Requirements)
step 4: Give Constraints and IBoutlets of controls.
step 5: In Viewcontroller,  give IBoutlet of UITableview and create delegate and data source.
step 6: In ViewDidload, register the cell. Like,

override func viewDidLoad() {
        super.viewDidLoad()
        
        self.tbl_view.register(UINib(nibName: "TableViewCell_json", bundle: nil), forCellReuseIdentifier: "TableViewCell_json")
        
        // Do any additional setup after loading the view.

    }

step 7: Create function of JSON Serialization. Like,

func call_API()
    {
        let url = URL(string: "URL")
        
        let task = URLSession.shared.dataTask(with: url!)
        {
            data, response, error in
            if error != nil
            {
                print(error)
            }
            else
            {
                if let url_Content = data
                {
                    do
                    {
                        self.json_Data = try JSONSerialization.jsonObject(with: url_Content, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSDictionary
                        print("JSON Serialization Data:",self.json_Data)

                        self.tbl_view.reloadData()
                    }
                    catch
                    {
                        print("json parsing error")
                    }
                }
            }
        }
        task.resume()
    }


step 8: Call the function in ViewDidload. Like,

override func viewDidLoad() {
        super.viewDidLoad()
        
        self.tbl_view.register(UINib(nibName: "TableViewCell_json", bundle: nil), forCellReuseIdentifier: "TableViewCell_json")

      call_API()

        // Do any additional setup after loading the view.
    }

step 9: In NumberofrowsInsection method put this code.

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        if json_Data.count != 0
        {
            return (json_Data["KEY"] as! NSArray).count
        }
        else
        {
            return 0
        }
        
    }

step 10: In cellforRowsAtIndexpath method put this code.

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell : TableViewCell_json = tableView.dequeueReusableCell(withIdentifier: "TableViewCell_json") as! TableViewCell_json
        
     let arr = (json_Data["hits"] as! NSArray)
     let temp_dict = (arr[indexPath.row] as! [String:AnyObject])

     cell.lbl_value.text = String((describing: temp_dict["id"] as? Int) ?? 0)
        return cell
    }



POST Method function of JSON Serialization.


func POSTMethod()
    {
     
        if let url = URL(string: "URL") {
            var request = URLRequest(url: url)
            request.httpMethod = "POST"
            let postString : String = "StudentId=2011111"
            request.httpBody = postString.data(using: String.Encoding.utf8)
            let task = URLSession.shared.dataTask(with: request)
            {
                data, response, error in
                if let data = data, let jsonString = String(data: data, encoding: String.Encoding.utf8), error == nil {
                   // completion(jsonString)
                    print(jsonString)
                } else {
                    print("error=\(error!.localizedDescription)")
                }
            }
            task.resume()
        }
    

    }

(Call this function on ViewDidLoad)

Get Image from URL...

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell : TableViewCell_json = tableView.dequeueReusableCell(withIdentifier: "TableViewCell_json") as! TableViewCell_json
        
        //Get Image from URL...
        let image_url = URL(string: ((self.json_Data["hits"] as! NSArray).object(at: indexPath.row) as! NSDictionary)["previewURL"] as! String)
        
        let session = URLSession(configuration: .default)
        let download_pic = session.dataTask(with: image_url!)
        {
            (data, responce, error) in
            if let e = error
            {
                print("Error download picture\(e)")
            }
            else
            {
                if let res = responce as? HTTPURLResponse
                {
                    print("Downloaded picture responce code\(res.statusCode)")
                    
                    if let image_data = data
                    {
                        let img_1 = UIImage(data: image_data)
                        
                        cell.img_pic.image = img_1
                    }
                    else
                    {
                        print("Could not get image")
                    }
                }
                else
                {
                    print("Could not get image code")
                }
            }
        }
        download_pic.resume()
        return cell

    }

Thank you...

No comments:

Post a Comment