[英]Swift: Async method into while loop
我想在while循環中使用異步函數,但是函數沒有足夠的時間來完成,而while循環再次啟動並且永遠不會結束。 我應該用增量變量來實現這個問題,但是解決方案是什么? 非常感謝。
輸入循環“進入重復” - “進入功能”
var condition = true
var userId = Int.random(1...1000)
repeat {
print("Into repeat")
checkId(userId, completionHandler: { (success:Bool) -> () in
if success {
condition = false
} else {
userId = Int.random(1...1000)
}
}) } while condition
func checkId(userId:Int,completionHandler: (success:Bool) -> ()) -> () {
print("Into function")
let query = PFUser.query()
query!.whereKey("userId", equalTo: userId)
query!.findObjectsInBackgroundWithBlock({ (object:[PFObject]?, error:NSError?) -> Void in
if object!.isEmpty {
completionHandler(success:false)
} else {
completionHandler(success:true)
}
})
}
您可以使用遞歸函數執行此操作。 我沒有測試過這段代碼,但我覺得它看起來有點像這樣
func asyncRepeater(userId:Int, foundIdCompletion: (userId:Int)->()){
checkId(userId, completionHandler: { (success:Bool) -> () in
if success {
foundIdCompletion(userId:userId)
} else {
asyncRepeater(userId:Int.random(1...1000), completionHandler: completionHandler)
}
})
}
你應該使用dispatch_group
repeat {
// define a dispatch_group
let dispatchGroup = dispatch_group_create()
dispatch_group_enter(dispatchGroup) // enter group
print("Into repeat")
checkId(userId, completionHandler: { (success:Bool) -> () in
if success {
condition = false
} else {
userId = Int.random(1...1000)
}
// leave group
dispatch_group_leave(dispatchGroup)
})
// this line block while loop until the async task above completed
dispatch_group_wait(dispatchGroup, DISPATCH_TIME_FOREVER)
} while condition
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.