Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift how to use NSTimer background?

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        var timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector:    Selector("update"), userInfo: nil, repeats: true)
    }

    func update() {
       println("Something cool")
    }
}

It's ok for the Simulator ,I will get continuous "Something cool" through I tapped the home button. But it worked out when I debug the app with my iPhone. I did't get anything when I tapped the home button and make my app run background. Someone told me I can play a long blank music to make my App run in the background.But I don't know how to play music in the background with swift @matt

like image 664
David Wang Avatar asked Jan 12 '15 03:01

David Wang


People also ask

Does NSTimer run in background?

Problem is, NSTimer requires an active run loop which is not always readily available on background queues. The main thread has an active run loop but this defeats the purpose of having our timer run in the background so its a definite no go. So, to get a dedicated background-queue-friendly timer, we use GCD.

How do I run an app in the background in Xcode?

You can configure your app to launch and run tasks in the background to take advantage of processing time when the device isn't used. To schedule a task to run in the background, enable the background modes in Xcode, identify the specific tasks that you need, and then register the tasks with the BGTaskScheduler object.


1 Answers

You can use beginBackgroundTaskWithExpirationHandler to get some background execution time.

class ViewController: UIViewController {
    var backgroundTaskIdentifier: UIBackgroundTaskIdentifier?

    override func viewDidLoad() {
        super.viewDidLoad()
        backgroundTaskIdentifier = UIApplication.sharedApplication().beginBackgroundTaskWithExpirationHandler({
            UIApplication.sharedApplication().endBackgroundTask(self.backgroundTaskIdentifier!)
        })
        var timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "update", userInfo: nil, repeats: true)
    }

    func update() {
        println("Something cool")
    }
}

Swift 3.0

backgroundTaskIdentifier = UIApplication.shared.beginBackgroundTask(expirationHandler: {
    UIApplication.shared.endBackgroundTask(self.backgroundTaskIdentifier!)
})

This code was inspired by this answer, but I ported to swift.

This apparently only runs for 3 minutes on iOS 7+.

like image 195
garetmckinley Avatar answered Nov 15 '22 06:11

garetmckinley