Eric Seo
Eric Seo

Reputation: 21

Break out of while loop after 5 seconds in Swift

I want to timeout and break out of this loop in 5 seconds. Only thing I could find online is having a count variable increment every second and then breaking if the count is 5, but was wondering if there's an easier, less codier way. Please help!

locationManager.startUpdatingLocation()
while (locationManager.location == nil) {
    //searching...
}
locationManager.stopUpdatingLocation()

Upvotes: 2

Views: 1361

Answers (2)

Alex Zanfir
Alex Zanfir

Reputation: 573

you can create a delay function like this:

func delay(delay:Double, closure:()->()) {

        dispatch_after(
            dispatch_time( DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC))), dispatch_get_main_queue(), closure)


    }

and after use it like this:

 delay(5){
locationManager.location = //something different from nil or you can try with break sentence ; not sure if with break will work though .

    }

Upvotes: 1

AlBlue
AlBlue

Reputation: 24040

The problem with having a while loop is that it will block the user's use of the application if it's on the main thread. Instead of doing that, you should start updating the location and then schedule a background thread using GCD (assuming you're on OSX; GCD isn't available on Linux yet) to run in a five seconds to disable the location manager. You could also schedule it to run in one second, check to see if it's present and then either attempt again or just let it run for five seconds.

Upvotes: 4

Related Questions