gpt4 book ai didi

swift - 函数在完成 block 完成之前返回

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

我在使用 Swifts GCD 时遇到问题。我有一个函数,可以在实际继续下载图像本身并将下载任务添加到数组之前检查以确保 token 有效。

问题是,如果 token 无效,在获取新 token 后,preloadImage 代码运行速度太快,导致 requestPreloadJWTToken 完成 block 无法设置 downloadTask 变量,因此它不是 nil。

以下是下载任务的设置。

static func preloadImage(sku: String)  {
// If the token exists AND is VALID (not expired) - Get the image.

let group = DispatchGroup()
var downloadTask : RetrieveImageDownloadTask? = nil

if ImageManager.tokenExists() && ImageManager.tokenIsNotExpired(){

let imageURL = ImageManager.URLBuilder(sku: sku)

// Create the request and add the token string to the authorization header
var urlRequest = try! URLRequest(url: URL(string: imageURL)!)
urlRequest.setValue("Bearer \(ImageManager.getTokenString()!)", forHTTPHeaderField: "Authorization")
downloadTask = NetRequest.downloadImage(urlRequest: urlRequest, sku: sku)
}
// Else if the token exists AND is INVALID (expired) - Delete the old token, get a new one, and fetch the image
else if ImageManager.tokenExists() && !ImageManager.tokenIsNotExpired(){
print("Token expired... Getting new token.")


_ = ImageManager.deleteToken()
if let tokenRequest = NetRequest.newTokenRequest(url: "http://\(UrlHelper.buildUrlFrom(SettingsManager.serverURL)){
group.enter()
tokenRequest.requestPreloadJWTToken(){
let imageURL = ImageManager.URLBuilder(sku: sku)

// Create the request and add the token string to the authorization header
var urlRequest = try! URLRequest(url: URL(string: imageURL)!)
urlRequest.setValue("Bearer \(ImageManager.getTokenString()!)", forHTTPHeaderField: "Authorization")

print("Token renewed. Fetching image...")
downloadTask = NetRequest.downloadImage(urlRequest: urlRequest, sku: sku)
}
group.leave()
}
}
// If the token doesn't exist, request a new one and fetch the image.
else{
print("Requesting new token...")

if let tokenRequest = NetRequest.newTokenRequest(url: "http://\(UrlHelper.buildUrlFrom(SettingsManager.serverURL)){
group.enter()
tokenRequest.requestPreloadJWTToken() {
print("Token aquired. Fetching image...")
let imageURL = ImageManager.URLBuilder(sku: sku)

// Create the request and add the token string to the authorization header
var urlRequest = try! URLRequest(url: URL(string: imageURL)!)
urlRequest.setValue("Bearer \(ImageManager.getTokenString()!)", forHTTPHeaderField: "Authorization")

downloadTask = NetRequest.downloadImage(urlRequest: urlRequest, sku: sku)
}
group.leave()
}
}
// This should always happen
group.notify(queue: DispatchQueue.main) {
MainController.imageDownloadTasks.append(downloadTask!)
}
}

下面是正在创建的 token 请求。

func requestPreloadJWTToken(completionHandler: @escaping () -> (/*RetrieveImageDownloadTask*/))
{
// Get the server name, username, and password
let username = SettingsManager.username
let password = SettingsManager.password

let queue = DispatchQueue(label: "Token-Request", qos: .utility, attributes: [.concurrent])

// Get download directory
let destination = DownloadRequest.suggestedDownloadDestination(for: .documentDirectory, in: .userDomainMask)

// Create the header to be used - Add username and password
self.makeURLRequest()
self.addPreAuthentication(username, password)

// Make the request for the token
Alamofire.download("\(UrlHelper.buildUrlFrom(SettingsManager.serverURL)), method: .post, parameters: nil, headers: self.request.allHTTPHeaderFields, to: destination)
// Alamofires built in authentication will provide credentials when challenged for authentication
.authenticate(user: username, password: password)
.responseString(
queue: queue,
completionHandler: { response in

DispatchQueue.main.async {
switch response.result {
// If the result was successful, the token string is saved to a file
case .success:
// Uncomment to see token string value
//debugPrint("Value \(response.value!)")
completionHandler()
case .failure(let error):
debugPrint("Failed \(error)")
}
}
}
)
}

如果有人对如何在 preloadImage 之前从 requestPreloadJWT 获取完成 block 有一些了解,那就太棒了。谢谢!

最佳答案

好吧。所以我在发表这篇文章后立即就明白了...当然...

无论如何。我只是将 group.leave() 粘贴在 preloadImage 方法中的闭包内,因此它看起来像:

static func preloadImage(sku: String)  {
// If the token exists AND is VALID (not expired) - Get the image.

let group = DispatchGroup()
var downloadTask : RetrieveImageDownloadTask? = nil

if ImageManager.tokenExists() && ImageManager.tokenIsNotExpired(){

let imageURL = ImageManager.URLBuilder(sku: sku)

// Create the request and add the token string to the authorization header
var urlRequest = try! URLRequest(url: URL(string: imageURL)!)
urlRequest.setValue("Bearer \(ImageManager.getTokenString()!)", forHTTPHeaderField: "Authorization")
downloadTask = NetRequest.downloadImage(urlRequest: urlRequest, sku: sku)
}
// Else if the token exists AND is INVALID (expired) - Delete the old token, get a new one, and fetch the image
else if ImageManager.tokenExists() && !ImageManager.tokenIsNotExpired(){
print("Token expired... Getting new token.")


_ = ImageManager.deleteToken()
if let tokenRequest = NetRequest.newTokenRequest(url: "http://\(UrlHelper.buildUrlFrom(SettingsManager.serverURL))"){
group.enter()
tokenRequest.requestPreloadJWTToken(){
let imageURL = ImageManager.URLBuilder(sku: sku)

// Create the request and add the token string to the authorization header
var urlRequest = try! URLRequest(url: URL(string: imageURL)!)
urlRequest.setValue("Bearer \(ImageManager.getTokenString()!)", forHTTPHeaderField: "Authorization")

print("Token renewed. Fetching image...")
downloadTask = NetRequest.downloadImage(urlRequest: urlRequest, sku: sku)
group.leave()
}
}
}
// If the token doesn't exist, request a new one and fetch the image.
else{
print("Requesting new token...")

if let tokenRequest = NetRequest.newTokenRequest(url: "http://\(UrlHelper.buildUrlFrom(SettingsManager.serverURL))"){
group.enter()
tokenRequest.requestPreloadJWTToken() {
print("Token aquired. Fetching image...")
let imageURL = ImageManager.URLBuilder(sku: sku)

// Create the request and add the token string to the authorization header
var urlRequest = try! URLRequest(url: URL(string: imageURL)!)
urlRequest.setValue("Bearer \(ImageManager.getTokenString()!)", forHTTPHeaderField: "Authorization")

downloadTask = NetRequest.downloadImage(urlRequest: urlRequest, sku: sku)
group.leave()
}
}
}
// This should always happen
group.notify(queue: DispatchQueue.main) {
MainController.imageDownloadTasks.append(downloadTask!)
}
}

希望这可以帮助遇到它的人!

关于swift - 函数在完成 block 完成之前返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46324490/

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