0

I get json data from url and I want return from function to variable and use it again

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
}

And usage from viewcontroller:

let result = getJsonLogin.getJson(urlGet: AppDelegate.ADDRESS+"/index.php", urlData: "mobile="+mobile+"")
print(result["message"])

I am beginner and i did not can solve this problem

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Abar New
  • 27
  • 2
  • 8

1 Answers1

1

The URLSession request is asynchronously.

So you need to set up a callback for retrieving the data. Like so:

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

Of course you could (and probably should) handle errors more properly than just passing nil. But for the sake of simplicity I just added the simplest I can think of, to fix your issue.

d4Rk
  • 6,622
  • 5
  • 46
  • 60
  • 1
    i use your code, but setTitle not work. how can i edit UIButton text? My code: let result = getJsonLogin.getJson(urlGet: AppDelegate.ADDRESS+"/index.php", urlData: "mobile="+mobile+"") { result in self.progressText.setTitle("x", for: UIControlState.normal) } } – Abar New Mar 03 '18 at 18:40