Stop / Pause swift app for period of time

2019-04-24 17:58发布

My app uses multiple threads of NSTimer Object.

Within the one function (called randomly at random times, not a fixed delay) I want it to pause the whole app, pause the threads for 1 second only. I have the following code:

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

Which is objective C, and I tried translating it into Swift like this:

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

But I am getting the error Missing argument for parameter 'waitUntilDone' in call and when I put that in, it says it wants the argument modes but when I put that in it says Extra argument modes.

I cannot figure out how to pause the app and all it's threads for a couple of seconds, and then carry on like normal?

Any ideas?

3条回答
相关推荐>>
2楼-- · 2019-04-24 18:15

Another way in Swift 3.1

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

You can substitute other units like .milliseconds(1000) or .microseconds(1_000_000) or .nanoseconds(1_000_000_000) for the time interval.

查看更多
小情绪 Triste *
3楼-- · 2019-04-24 18:24

The performSelector methods aren't available in Swift. You can get the delay functionality by using dispatch_after.

let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(NSEC_PER_SEC * 1))
dispatch_after(delayTime, dispatch_get_main_queue()){
    changeColourOfPage() 
}
查看更多
太酷不给撩
4楼-- · 2019-04-24 18:28

Sorry to answer an old question, but just came along a better way to do this -

import Darwin //Put this line at the beginning of your file
func pauseForAMoment() {

        sleep(1)
        changeColorOfPage()

}
查看更多
登录 后发表回答