Swift从函数完成中获取值并将其设置为全局变量

时间:2017-09-04 19:58:19

标签: json swift function global-variables completion

我试图从函数的竞争中获取变量,并将其转换为全局变量。这是我打电话的功能:

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

这就是我所说的:

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

但是,我想将ips从我称之为全局变量的地方转变。目前,我在ViewController外面有一个名为ip2的变量,这就是我尝试设置变量的方法:

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

并没有将ip2设置为ips的值。你怎么能这样做?

1 个答案:

答案 0 :(得分:0)

我认为问题是因为URLSession是异步任务。试试这可能会有所帮助:

更改您定义ip2变量的方式,如下所示:

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