Swift:返回json数据

时间:2018-03-02 19:53:53

标签: ios json swift

我从url获取json数据,我想从函数返回变量 并再次使用

 button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Uri uri = Uri.parse("http://google.com");
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                startActivity(intent); ***<--- error!***
        }

来自viewcontroller的用法:

internal func getJson(urlGet:String, urlData:String){
    let urlFind = URL(string: urlGet)
    var request = URLRequest(url: urlFind!)
    request.httpMethod = "POST"
    request.httpBody = urlData.data(using: .utf8)

    var firstDataGet = [firstData]()

    URLSession.shared.dataTask(with:request, completionHandler: {(data, response, error) in
        guard let data = data, error == nil else { return }
        print(urlGet)

        do {
            let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! [String:String]
            print(json)

        } catch let error as NSError {
            json = nil
        }
    }).resume()

    return json
}

我是初学者,我没有能解决这个问题

1 个答案:

答案 0 :(得分:0)

URLSession请求是异步的。

因此,您需要设置回调以检索数据。像这样:

internal func getJson(urlGet: String, urlData: String, completion: @escaping ([String:String]?) -> Void) {
    let urlFind = URL(string: urlGet)
    var request = URLRequest(url: urlFind!)
    request.httpMethod = "POST"
    request.httpBody = urlData.data(using: .utf8)

    var firstDataGet = [firstData]()

    URLSession.shared.dataTask(with:request, completionHandler: { (data, response, error) in
        guard let data = data, error == nil else { return }
        print(urlGet)

        do {
            let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! [String:String]
            print(json)
            completion(json)

        } catch let error as NSError {
            json = nil
            completion(nil)
        }
    }).resume()
}


let result = getJsonLogin.getJson(urlGet: AppDelegate.ADDRESS+"/index.php", urlData: "mobile="+mobile+"") { result in
    print(result)
}

当然,你可以(并且可能应该)更正确地处理错误,而不仅仅是传递nil。但为了简单起见,我只是添加了我能想到的最简单的方法来修复你的问题。