Thursday, 28 December 2017

Download image from JSON(Using SDWebImage and Without use SDWebImage)

Using SDWebImage:-

step 1: Install pods of SDWebImage and import DSWebImage in your viewController.
step 2: You can call and display JSON data using Alamofire / JSONSerialization.
step 3: If you are use UITableviewcontroller, than in CellForRowAtIndexPath put this code. Like,

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)
        
        cell.img_pic.sd_setImage(with: URL(string: ((self.json_Data["hits"] as! NSArray).object(at: indexPath.row) as! NSDictionary)["previewURL"] as! String), placeholderImage: #imageLiteral(resourceName: "cool-wild-animal-wallpaper-high-quality-For-Desktop-Wallpaper"), options: SDWebImageOptions.cacheMemoryOnly, completed: nil)
        
        return cell

    }

Without using SDWebImage:-

step 1: You can call and display JSON data using Alamofire / JSONSerialization.
step 2: If you are use UITableviewcontroller, than in CellForRowAtIndexPath put this code. Like,

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