gpt4 book ai didi

swift - 如何使快速http请求功能同步/完成处理

转载 作者:行者123 更新时间:2023-11-28 13:30:25 30 4
gpt4 key购买 nike

<分区>

我创建了一个同步函数来登录用户,但是该函数内部的 http 请求是异步的,因此父函数在异步部分发生之前返回 false。我知道我必须以某种方式将 signingInExtension 转换为具有完成处理的异步函数,然后以不同于 viewDidLoad 函数的方式调用它,我只是想不出语法。

此外,http 请求带有一个 completionHandler,但我不明白如何修改它以将其返回值传递到调用它的位置。

 override func viewDidLoad() {
signedIn = signingInExtension()
}

func signingInExtension() -> Bool {
if (self.singleUseIdentityToken != nil) {
if (!tokenExpired(t: self.singleUseIdentityToken)) {
let parameters = [
"method": "single-use-identity-token",
"token": self.singleUseIdentityToken!
] as [String : Any]
let url = URL(string: self.endpoint + "/auth/signin")!
let session = URLSession.shared
var request = URLRequest(url: url)
request.httpMethod = "POST"
do {
request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted)
} catch let error {
print(error.localizedDescription)
}
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")

let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in

guard error == nil else {
return
}

guard let data = data else {
return
}

do {
if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] {
if (json["token"] == nil) {
return
} else {
print(json["token"] as! String)
// store token in file
// here I would like signingInExtension to return true
// but it already returned false because I am not handling async correctly
}
}
} catch let error {
print(error.localizedDescription)
}
})
task.resume()
}
}
return false // this happens before task
}

我如何从 http 任务完成处理程序中返回 truefalse 一直到我调用 signingInExtension 的地方?

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