我正在尝试从外部JSON文件中获取一个字符串,该文件位于Web服务器上,并且它成功获取它,但它在一个闭包中,它获取了值,我需要将它放到外面所以我可以用变量returnip返回它我该怎么做?
func getJsonFromUrl() -> String {
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)
} else {
do {
let parsedData = try JSONSerialization.jsonObject(with: data!) as! [String:Any]
let ips = parsedData["ip"] as! String
print("The IP is: " + ips) //Prints the value correctly
var returnip = ips //The value that I want to return, that does not go outside this closure
} catch let error as NSError {
print(error)
}
}
}.resume()
return returnip //Does not return anything
}
由于
答案 0 :(得分:1)
您无法从异步函数返回,并且闭包内的return语句仅从闭包本身返回。
您需要使用完成处理程序。此外,在解析网络响应时,请勿使用强制解包选项/强制转换选项。
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: "Input", completion: { ips in
print(ips)
//you can only use the value inside the closure of completion
})