0

I am making JSON request and if its completed so I am navigating page with JSON data to my table view controller and everything works fine but when I am making second call to load more cells I am not able to reload data and here is the code of my table view controller there I am making second call.

    var listData:[String] = []
    var videoIDData:[String] = []
    var valueKeyData:[String] = []
    var nextPageToken:String?
    var titleNamee:[String] = []
    var videoIDD :[String] = []
    var valueKeyy :[String] = []
    var PrevPageToken:String?



    @IBOutlet weak var tableView: UITableView!


    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.delegate = self
        tableView.dataSource = self
    }

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

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
               return listData.count
    }


    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
      let cell = tableView.dequeueReusableCell(withIdentifier: "VideoCell", for: indexPath) as! VideoTableViewCell
        cell.videoTitle.text = listData[indexPath.row]
        let url = NSURL(string: valueKeyData[indexPath.row])
        let dataaa = NSData(contentsOf: url! as URL)
        let image = UIImage(data: dataaa! as Data)
        cell.videoThumnailImageView.image = image


        if (indexPath.row == listData.count - 1)
        {
            makeGetCall()

        }




     return cell
     }

    func makeGetCall() {
        // Set up the URL request
        var pageToken:String = (pageToken)
        let todoEndpoint: String = "https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=50\(pageToken)&playlistId=\(id)_ItOZ8WBF5_SI_SrSN3_F&\(key)"

        guard let url = URL(string: todoEndpoint) else {
            print("Error: cannot create URL")
            return
        }
        let urlRequest = URLRequest(url: url)

        // set up the session
        let config = URLSessionConfiguration.default
        let session = URLSession(configuration: config)

        // make the request
        let task = session.dataTask(with: urlRequest) {
            (data, response, error) in
            // check for any errors
            guard error == nil else {
                print("error calling GET on /todos/1")
                print(error)
                return
            }

            guard let responseData = data else {
                print("Error: did not receive data")
                return
            }
            // parse the result as JSON, since that's what the API provides
            do {
                guard let jsonObject = try JSONSerialization.jsonObject(with: responseData, options: []) as? [String : AnyObject]  else {
                    print("error trying to convert data to JSON")

                    return
                }
                self.PrevPageToken = jsonObject["prevPageToken"] as? String
                self.nextPageToken = jsonObject["nextPageToken"] as? String
                    if let itemsArray = jsonObject["items"] as? [[String:AnyObject]]{
                        for snippetArray in itemsArray{
                            if var snippet = snippetArray["snippet"] as? [String : AnyObject]{
                                if let titleItems = snippet["title"] as? String{
                                    self.titleNamee += [titleItems]
                                }
                                if let thumbnail = snippet["thumbnails"] as? [String : AnyObject]{
                                    if let highValue = thumbnail["high"] as? [String : AnyObject]{
                                        if let urlValueKey = highValue ["url"] as? String{
                                            self.valueKeyy += [urlValueKey]
                                        }
                                    }
                                }
                                if let resource = snippet["resourceId"] as? [String : AnyObject]{
                                    if let videoId = resource["videoId"] as? String{
                                        // self.videoIDD.append(videoId)
                                        self.videoIDD += [videoId]
                                    }
                                }
                            }
                        }
                }

            } catch  {
                print("error trying to convert data to JSON")
                return
            }
        }

        task.resume()

        DispatchQueue.main.async{
            self.tableView.reloadData()
        }

    }

 }
2
  • You have to try with Model Class in the place of Multiple Array all of the contents which are you going to pass inside table view and after getting second JSON you have to call your table reload code inside the main dispatch because the block is async that's why unable to perform Table reload. Commented May 31, 2017 at 5:40
  • I have created the NSObject custom class but I am not getting how can I use this class in this method.. any help plz...??? Commented Jun 4, 2017 at 0:25

1 Answer 1

2

You are reloading tableView at wrong place you need to reload it inside completion block after the for loop because completion block will call async, so remove your current reload code of tableView and put it after the for loop.

for snippetArray in itemsArray{
    if var snippet = snippetArray["snippet"] as? [String : AnyObject]{
        if let titleItems = snippet["title"] as? String{
            self.titleNamee += [titleItems]
        }
        if let thumbnail = snippet["thumbnails"] as? [String : AnyObject]{
            if let highValue = thumbnail["high"] as? [String : AnyObject]{
                if let urlValueKey = highValue ["url"] as? String{
                    self.valueKeyy += [urlValueKey]
                }
            }
        }
        if let resource = snippet["resourceId"] as? [String : AnyObject]{
            if let videoId = resource["videoId"] as? String{
                // self.videoIDD.append(videoId)
                self.videoIDD += [videoId]
            }
        }
    }
}
//Reload your table here
DispatchQueue.main.async{
    self.tableView.reloadData()
}

Note: Instead of creating multiple array that you are doing currently what you need to do is make one custom class or struct with all these properties and make array of that custom class or struct objects.

Edit: I haven't looked at that you are calling this method in cellForRowAt don't do that as of cell will be reused and that is the reason you UI getting stuck so remove that calling code from cellForRowAt, if you want to make something like pagination than you can use scrollViewDelegate method like this way.

func scrollViewDidScroll(_ scrollView: UIScrollView) {
    if((scrollView.contentOffset.y + scrollView.frame.size.height) == scrollView.contentSize.height)
    {
        self.makeGetCall()
    }
}

Also it its better that you show some process indicator while you are making API request.

Sign up to request clarification or add additional context in comments.

6 Comments

thanks for your reply... I tried like this way but still its not reloading the data .. it got stuck always on the very last cell.... but when I am printing each Array it showing data...
@User786 What do you mean by it got stuck is it crashing the app ? if it is crashing at cellForRowAt with one for the line where you are subscripting your array with indexPath.row then all your array not having equal objects
No its not crashing .... its stucking when I am scroll up and its calling function makeGetCall() again n again.... and when I debug function is parsing data equally in all arrays... but not reloading cells.
Yeah ... thanks for your help n reply... its working n reloading data on table view but the only issue is stucking n then reloading data... but atleast its working...
@User786 Welcome mate :)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.