Search code examples
iosjsonswiftgetalamofire

Unable to save JSON data from Alamofire GET request to local variables of function


I'm trying to save the data from the Alamofire GET request. But when I make count equal to the json data given by the value method, I still return 0..What's the best way to save the values given by the GET request to local variables?

func loadInstallerCount() -> Int {
        var count: Int = 0
        Alamofire.request(URL, method: .get, parameters: nil, encoding: JSONEncoding.default, headers: nil).responseJSON { response in
            //print("String:\(String(describing: response.result.value))")

            if let data = response.result.value{
                let jsonData = data as! NSDictionary
                if(!(jsonData.value(forKey: "error") as! Bool)) {
                    //getting the user from response
                    count = jsonData.value(forKey: "installationcount") as! Int
                }else{
                    //error message in case of invalid credential
                    print("couldn't get count")
                }
            }
        }
        return count
    }

Solution

  • Use closure for that purpose as it is asynchronous. Example:

    func callTheFunction(){
        loadInstallerCount { (count) in
            print(count)
        }
    }
    
    func loadInstallerCount(result:(_:Int) -> Void) {
        var count: Int = 0
        Alamofire.request(URL, method: .get, parameters: nil, encoding: JSONEncoding.default, headers: nil).responseJSON { response in
            //print("String:\(String(describing: response.result.value))")
    
            if let data = response.result.value{
                let jsonData = data as! NSDictionary
                if(!(jsonData.value(forKey: "error") as! Bool)) {
                    //getting the user from response
                    count = jsonData.value(forKey: "installationcount") as! Int
                }else{
                    //error message in case of invalid credential
                    print("couldn't get count")
                }
                result(count)
            }
        }
    
    }