gpt4 book ai didi

swift - 如何查询 php 页面并保存它返回给我的值?

转载 作者:行者123 更新时间:2023-11-30 10:46:10 24 4
gpt4 key购买 nike

用 Swift 构建的应用程序的目的是读取一个值,将其发送到一个 php 页面,该页面返回一个与 url 相对应的值。随后该 url 将在要显示的 webView 中设置。

目前我的应用程序发送值,我可以获取字符串格式的 url。我的问题是,如果我在 URLSession.shared.dataTask 进程之外使用该变量,则该变量为空。

网上查了一下,原因是该操作是在另一个线程中执行的,那么如何保持该值的持久化呢?

我正在使用 swift 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
}

最佳答案

您可以使用闭包:

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

Apple Developer Documentation

关于swift - 如何查询 php 页面并保存它返回给我的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55730239/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com