Swift内置应用程序的目的是读取一个值,并将其发送到一个php页面,该页面返回与URL对应的值。随后,将在要显示的webView中设置该网址。
当前,我的应用程序发送该值,并且我可以获取字符串格式的url。我的问题是,如果我在URLSession.shared.dataTask进程之外使用该变量,则该变量为空。
在Internet上搜索时,我发现原因是该操作是在另一个线程中执行的,那么如何保持该值的持久性?
我正在迅速开发4.2
func risolutoreIndirizzo() -> String {
var addressURL:String = ""
let domain = "https://mywebsite.com/"
let domain = "getUrl.php"
print("URL -> \(domain+domain)")
let request = NSMutableURLRequest(url: NSURL(string: domain+domain)! as URL)
request.httpMethod = "POST"
let nameDB = "SVILUPPO"
let postString = "StringaAccesso=\(nameDB)"
request.httpBody = postString.data(using: String.Encoding.utf8)
let task = URLSession.shared.dataTask(with: request as URLRequest) {
data, response, error in
if error != nil {
print("error=\(String(describing: error))")
return
}
//print("response = \(response)")
let responseString:String! = NSString(data: data!, encoding: String.Encoding.utf8.rawValue) as String?
print("responseString = \(String(describing: responseString))")
print("---------------------------------")
let arrayResponse = responseString.split(separator: ",")
//print(arrayResponse[0])
addressURL = arrayResponse[0].split(separator: ":")[1] + ":" + arrayResponse[0].split(separator: ":")[2]
print("AddressURL -> " + addressURL)//Here I see correctly -> https://mywebsite.com/privateProject
stringURl = addressURL //stringURl initialized at the beginning of the code
}
task.resume()
print("URL -> " + stringURl)//Here the variable is empty
return addressURL
}
答案 0 :(得分:0)
您可以使用闭包:
func risolutoreIndirizzo(completion: @escaping (_ result: String) -> Void) {
...
let task = URLSession.shared.dataTask(with: request as URLRequest) {
data, response, error in
...
completion(addressURL)
}
...
}
使用:
risolutoreIndirizzo() { address in
print(address)
}