Vinayak Bhor
Vinayak Bhor

Reputation: 691

Refresh Alamofire Request after few seconds not working properly

  1. I used timer in viewdidload with selector function

eg.

var timer = Timer.scheduledTimer(timeInterval: 0.4, target: self,selector: #selector(HomeViewController.getRequest), userInfo: nil, repeats: true)
  1. getRequest() used for json parsing with alamofire and used collection view to populate the data

  2. timer and function run properly but on json Data appended into array continuously. On view collection view Data appearing continuously.

  3. I want to just refresh Alamofire request after few seconds but not whole function because json data push into arrays and dictionary.

my getRequest() code:

func getRequest() {

     let getUserID :UserDefaults = UserDefaults.standard

     let parameters: Parameters = [

        "user_id" : getUserID.value(forKey: "user_id")!

    ]

    Alamofire.request(URL_String, method: .post, parameters: parameters).responseJSON{


        (response) in


        print(" url :\(response.request)")

        guard response.result.isSuccess  else {

            print("Block 1 ")


            print(" response :\(response)")

            print("Error with response: \(String(describing: response.result.error))")
            return
        }
        guard let dict = response.result.value as? Dictionary <String,AnyObject>


            else {

            print(" response :\(response)")

            print("Error with dictionary: \(String(describing: response.result.error))")
            return
        }

        guard let dictData = dict["message"] as? [Dictionary <String,AnyObject>] else {

            print("Error with dictionary data: \(String(describing: response.result.error))")

            return
        }

        for data in dictData{

            self.lawNameArray.append(data["title"] as! String)
            self.lawImageArray.append(data["law_images"] as! String)
            self.dataArray.append(data["title"] as! String)
            print("lawNameArray..............\(self.lawNameArray)")
            print("lawImageArray..............\(self.lawImageArray)")

            self.lawIdArray.append(data["law_id"] as! String)
            self.lawStatusArray.append(data["status"] as! String)

            print("law Id Array :\(self.lawIdArray)")

            print("Data array :\(self.dataArray)")

        }
        self.myActivityIndicator.stopAnimating()
        self.myActivityIndicator.hidesWhenStopped = true
        self.collectionView.reloadData()
        print(" dict data\(dictData)")

    }


}

Upvotes: 2

Views: 315

Answers (1)

Moayad Al kouz
Moayad Al kouz

Reputation: 1392

I guess you need to empty arrays before appending new data, So you may add below code before for loop:

self.lawNameArray.removeAll()
self.lawImageArray.removeAll()
self.dataArray.removeAll()
self.lawIdArray.removeAll()
self.lawStatusArray.removeAll()

Upvotes: 1

Related Questions