Swift get value from function completion and set it to a global variable

514 views Asked by At

I am trying to get the variable from the competition on a function, and turn it into a global variable. This is the function I'm calling:

func getJsonFromUrl(name: String, completion: @escaping (String?)->()) {
//use name variable just as you would in a normal function
let URL2 = "https://url.com/asd.php"
let url = URL(string: URL2)
URLSession.shared.dataTask(with:url!) { (data, response, error) in
    if error != nil {
        print(error as Any)
        completion(nil)
    } else {
        do {
            guard let parsedData = try JSONSerialization.jsonObject(with: data!) as? [String:Any] else { completion(nil); return }
            guard let ips = parsedData["ip"] as? String else {completion(nil); return }
            print("The IP is: " + ips) //Prints the value correctly
            completion(ips)
        } catch let error as NSError {
            print(error)
            completion(nil)
        }
    }
}.resume()
}

This is how I call it:

 getJsonFromUrl(name: "Bob", completion: { ips in
            print(ips)
        })

However, I want to turn ips from where I call it to a global variable. Currently, I have a variable stated outside the ViewController called ip2, and this is how I tried setting the variable:

 getJsonFromUrl(name: "Bob", completion: { ips in
            print(ips)
            ip2 = ips!
        })

And it's not setting ip2 to the value of ips. How can you do this?

1

There are 1 answers

6
Tung Vu Duc On

I think the problem because the URLSession is async task. try this it might can help :

change the way you define ip2 variable like this :

var ip2 : String = "" {
    didSet {
       //Do something when ip2 get the value
    }
}