代码之家  ›  专栏  ›  技术社区  ›  buttonSmasher96

无法将Alamofire GET请求中的JSON数据保存到函数的局部变量

  •  0
  • buttonSmasher96  · 技术社区  · 7 年前

    我正在尝试保存Alamofire GET请求中的数据。但当我使count等于value方法给出的json数据时,我仍然返回0。。将GET请求给出的值保存到局部变量的最佳方法是什么?

    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
        }
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   Y_Y    7 年前

    为此,请使用闭包,因为它是异步的。示例:

    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)
            }
        }
    
    }