Stop / pause a quick application for a period of time

My application uses multiple threads of an NSTimer Object.

As part of a single function (called randomly at random times, rather than a fixed delay), I want it to pause the entire application, suspend threads for only 1 second . I have the following code:

 [self performSelector:@selector(subscribe) withObject:self afterDelay:3.0 ]; 

Which is objective C, and I tried to translate it into Swift as follows:

 self.performSelector(Selector:changeColourOfPage(), withObject: self, afterDelay: 1.0) 

But I get the error message Missing argument for parameter 'waitUntilDone' in call , and when I insert it, it says that it needs the modes argument, but when I put it, it says Extra argument modes .

I can’t figure out how to pause the application and all its threads for a couple of seconds, and then continue as usual?

Any ideas?

+6
source share
3 answers

The performSelector methods are not available in Swift. You can get the delay functionality using dispatch_after.

 let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(NSEC_PER_SEC * 1)) dispatch_after(delayTime, dispatch_get_main_queue()){ changeColourOfPage() } 
+11
source

Sorry to answer the old question, but came up with a better way to do this -

 import Darwin //Put this line at the beginning of your file func pauseForAMoment() { sleep(1) changeColorOfPage() } 
0
source

Another way in Swift 3.1

 DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(1)) { changeColourOfPage() } 

You can replace other units, such as .milliseconds(1000) or .microseconds(1_000_000) or .nanoseconds(1_000_000_000) with a time interval.

0
source

Source: https://habr.com/ru/post/972147/


All Articles