Search code examples
iosswiftbackground-processnsthread

How do I stop this NSThread?


I've got a function that gets called when my app enters background mode. I''d like to stop the thread if user re-opens the app. Nothing I'm trying works so far though.

Here's my code so far:

class Neversleep {
    private static var callback : (()->Void)?
    private static var thread: NSThread?

    static func start(callback: ()->Void) {
        self.callback = callback

        Neversleep.thread = NSThread(target: self, selector: #selector(Neversleep.task), object: nil)
        Neversleep.thread?.start()

    }

    static func stop() {
        print("NEVERSLEEP:STOP")
        Neversleep.thread?.cancel()

    }

    @objc static func task() {

        while (true)
        {
            sleep(3);
            print("we are still running!")
            callback?()
        }
    }
}

I call Neversleep.start() from app Delegate's DidEnterBackground method.

I'm calling Neversleep.stop() from willEnterForeground...but it's not stopping the thread.

I'm sure I'm missing something obvious here. But what?


Solution

  • Calling cancel on a thread doesn't automatically kill the thread. The actual body of the thread needs to stop whatever it is doing when its thread is cancelled.

    Update your task function like this:

    @objc static func task() {
        while (!NSThread.currentThread.cancelled)
        {
            sleep(3);
            print("we are still running!")
            callback?()
        }
    }
    

    Double check the actual method and property names for currentThread and cancelled. I'm not 100% sure what they are named in Swift 2.

    Even with the above, you will likely get one more call to callback after the thread is cancelled due to the sleep. You can fix this with:

    @objc static func task() {
        while (!NSThread.currentThread.cancelled)
        {
            sleep(3);
            print("we are still running!")
            if (!NSThread.currentThread.cancelled) {
                callback?()
            }
        }
    }