0

I work with Alamofire and SwiftyJSON and have function:

func getCitiesFromServer(){

    Alamofire.request("mysite", method: .get, encoding: JSONEncoding.default, headers: nil)
        .responseJSON { response in

            switch response.result {
            case .success:
                var json = JSON(response.result.value!)

                for i in 0..<json["cities"].count {

                    self.dictOfCities[json["cities"][i]["id"].int!] = json["cities"][i]["name"].string
                }


            case .failure(let error):
                print(error)
            }

    }

}

And I'd like to work with dictOfCities when I create tableView, but how return dictOfCities in getCitiesFromServer()? I try print(dictOfCities) at the end of getCitiesFromServer(), but see only [:], but in part case .success: I see good key-value.

Vadim Nikolaev
  • 2,132
  • 17
  • 34

2 Answers2

1

Alamofire use asynchronous request process. (recommended to avoid blocking UI)

I suggest using closures.

func getCitiesFromServer() {
  // execute Alamofire request
}

becomes

func getCitiesFromServer(completion:((_ success: Bool, _ result: [String]?)->Void)?) {
  // execute Alamofire request
  // call closure (if present) with result parameters
  completion?(success, ["a", "b"])
}

And called like this :

// execute HTTP request via getCitiesFromServer()
getCitiesFromServer() { (success, result) in
  // call closure after request execution
}
Florent Morin
  • 842
  • 1
  • 10
  • 13
0

I normally work with the completionHandler Pattern in Swift to return my json asynchronously. So in your example you just have to add an completionHandler in your function call like this:

func getCitiesFromServer(result: ([Int]) -> ()){

Alamofire.request("mysite", method: .get, encoding: JSONEncoding.default, headers: nil)
    .responseJSON { response in

        switch response.result {
        case .success:
            var json = JSON(response.result.value!)
            var dictOfCities = [Int]()
            for i in 0..<json["cities"].count {

                dictOfCities[json["cities"][i]["id"].int!] = json["cities"][i]["name"].string
            }
            result(dictOfCities);

        case .failure(let error):
            print(error)
        }

}

}

This is also shown here and in many other tutorials. I don't have tested this code yet, but maybe it will give you an advice how to do it. In your TableView you just have to react with the same pattern when the data comes finally in and render the view with reloadData().

In VC:

var rowLabels = [Int]() {
        didSet {
            self.tableView.reloadData()
            //Other functions
        }
    }

In VC to fetch data:

getCitiesFromServer({
            result in
            if let ids= result{
                self.rowLabels = ids
            } else {
                self.rowLabels = [Int]()
            }
        })
Mo0812
  • 140
  • 2
  • 12
  • http://stackoverflow.com/questions/27390656/how-to-return-value-from-alamofire – Mo0812 Jan 17 '17 at 13:55
  • ok, but how return count of keys in my Dictionary in `func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {}`, for example? – Vadim Nikolaev Jan 17 '17 at 13:57
  • just create in your ViewController an empty Dictionary and use dict.count. I prefer to use the didSet observer in the variable and call an reloadData() in there when my request function gives back new data. - see the update above – Mo0812 Jan 17 '17 at 14:04