【问题标题】:Unable to save JSON data from Alamofire GET request to local variables of function无法将来自 Alamofire GET 请求的 JSON 数据保存到函数的局部变量
【发布时间】:2018-05-10 00:49:40
【问题描述】:

我正在尝试保存来自 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
    }

【问题讨论】:

  • installationcount包含的值是什么?你能告诉我们你的 json 响应吗?
  • “安装次数”:19

标签: ios json swift get alamofire


【解决方案1】:

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

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

}

【讨论】:

  • 它打印正确的数量,19。但是我如何从 callTheFunction 返回值?我不想打印它,我想存储它以将它传递给一个函数。
  • 用你的函数替换闭包内的 print 并将计数传递给它。
猜你喜欢
  • 1970-01-01
  • 2017-09-02
  • 2019-08-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-05
  • 2018-02-22
  • 1970-01-01
相关资源
最近更新 更多