gpt4 book ai didi

swift - 使用调度组时关闭丢失

转载 作者:搜寻专家 更新时间:2023-11-01 06:51:06 24 4
gpt4 key购买 nike

调度代码未调用。当我调用 reLog() 方法时,它没有执行 DispatchQueue.main.async block 中编写的代码。

       func reLog() -> Bool {
var isVerified = false
let group = DispatchGroup()
group.enter()
DispatchQueue.global(qos: .default).async {
self.login({ () -> Void in
isVerified = true
group.leave()
}, fail: { (failureDict) -> Void in
group.leave()
})
}
group.wait()
return isVerified
}


func login(_ success : (()-> Void), fail : (()-> Void)){
let session = URLSession(configuration: .default, delegate: self, delegateQueue: nil)
let task = session.dataTask(with: urlRequest){
(data, response, error) -> Void in
DispatchQueue.main.async(execute: { () -> Void in
print("Testing") // This closure not calling
})
})
task.resume()
}

现在这是我的要求。我需要实现它,因为我需要服务器响应才能继续循环。

for i in strings {
let isLogged = relog()
if isLogged {
print("Successful")
}
}

最佳答案

你需要在里面login

task.resume()

替换

group.wait() 
return isVerified

group.notify(queue:.main) {
completion(isVerified)
}

func reLog(completion:@escaping(Bool) -> ())

编辑

func reLog(completion:@escaping(Bool) -> ())
var isVerified = false
let group = DispatchGroup()
group.enter()
DispatchQueue.global(qos: .default).async {
self.login({ () -> Void in
isVerified = true
group.leave()
}, fail: { (failureDict) -> Void in
group.leave()
})
}
group.notify(queue:.main) {
completion(isVerified)
}
}

打电话

 reLog {  isVerified in
print(isVerified)
}

关于swift - 使用调度组时关闭丢失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56969370/

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