简体   繁体   中英

Swift: Async method into while loop

I want to use a async function inside a while loop but the function don't get enough time to finish and the while loop starts again and never ends. I should implement this problem with increment variable , but what is the solution? thanks a lot.
output loops between "Into repeat" - "Into function"

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

You can do this with a recursive function. I haven't tested this code but I think it could look a bit like this

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

You should use 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

See more at Apple document

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM