Swift how to use NSTimer background?

how to run timer in background ios
dispatchsourcetimer
ios keep app alive in background swift
swift timer
swift timer not firing
play audio in background ios swift
swift timer notification
timer stops in background ios
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

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+.

A Background Repeating Timer in Swift - Over Engineering, So, to get a dedicated background-queue-friendly timer, we use GCD. Hello DispatchSourceTimer. Like most APIs we deal with from Apple,  You will need to use Timer instead of NSTimer in Swift 3. Here is an example: Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(YourController.update), userInfo: nil, repeats: true) func update() { // do what should happen when timer triggers an event }

I'm willing to bet that you don't need to run a timer in the background, what you need is to know the time that has elapsed while you were suspended. That is a much better use of your resources than trying to play an empty sound file.

Use applicationWillResignActive and applicationDidBecomeActive to determine how much time has elapsed. First save the fireDate of your timer and invalidate it in applicationWillResignActive

func applicationWillResignActive(application: UIApplication) {
    guard let t = self.timer else { return }
    nextFireDate = t.fireDate
    t.invalidate()
}

Next, determine how much time is left for the timer in applicationDidBecomeActive by comparing the time now to the fireDate you saved in the applicationWillResignActive call:

func applicationDidBecomeActive(application: UIApplication) {
    guard let n = nextFireDate else { return }
    let howMuchLonger = n.timeIntervalSinceDate(NSDate())
    if howMuchLonger < 0 {
        print("Should have already fired \(howMuchLonger) seconds ago")
        target!.performSelector(selector!)
    } else {
        print("should fire in \(howMuchLonger) seconds")
        NSTimer.scheduledTimerWithTimeInterval(howMuchLonger, target: target!, selector: selector!, userInfo: nil, repeats: false)
    }
}

If you need a repeating one, just do math to figure out how many times the timer should have fired while in the background

let howManyTimes = abs(howMuchLonger) / repeatInterval

iOS Timer Tutorial, How to run timer in background for unlimited time while iphone screen locked or Use the. Thread API to start your own thread for this (see my Swift Forums  swift use NSTimer in app background. Webapp Codes offers thousands of free tutorials and codes for IT professionals, hobbyists, and home users.

when I tapped the home button and make my app run background

No, that's a false assumption. When you tap the home button, you do not make your app run in the background. You make your app suspend in the background. Your code does not run when you are in the background.

Apps can get special permission to run in the background just in order to perform certain limited activities, like continuing to play music or continuing to use Core Location. But your app does none of those things, so it goes into the background and stops.

How to run timer in background for…, We will be using the same for writing our code for running the timer in background. So let's begin. Step 1 − Open Xcode → Single View  Is there REALLY any SOLID solution to running an NSTimer in background? Unfortunately, there is no reliable way to periodically run some actions while in background. You can make use of background fetches, however the OS doesn't guarantee you that those will be periodically executed.

add this code in appdelegate for run a task in background , its working finely,

var backgroundUpdateTask: UIBackgroundTaskIdentifier = 0

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    return true
}

func applicationWillResignActive(application: UIApplication) {
    self.backgroundUpdateTask = UIApplication.sharedApplication().beginBackgroundTaskWithExpirationHandler({
        self.endBackgroundUpdateTask()
    })
}

func endBackgroundUpdateTask() {
    UIApplication.sharedApplication().endBackgroundTask(self.backgroundUpdateTask)
    self.backgroundUpdateTask = UIBackgroundTaskInvalid
}

func applicationWillEnterForeground(application: UIApplication) {
    self.endBackgroundUpdateTask()
}

How to run a timer in background within your iOS app, For example, we could pass in a dictionary containing a username: let context = ["​user": "@twostraws"] Timer.scheduledTimer(timeInterval: 1.0  Drag two buttons under the label and next to each other. On the button to the left, title it Start, make the font blackwith a size of 46 pointsand a green background. On the right title the label Stopwith a size of 46 points, whitelettering and a redbackground. Pin the Startlabel 15 points up, and 0 left.

The ultimate guide to Timer – Hacking with Swift, Timer with RunLoop. Most of the time when using Timers you would want your timer to run in the background while you are busy doing something  Use the timer With Time Interval: invocation: repeats: or timer With Time Interval: target: selector: user Info: repeats: class method to create the timer object without scheduling it on a run loop. (After creating it, you must add the timer to a run loop manually by calling the add Timer: for Mode: method of the corresponding NSRun Loop object.)

Easy Swift Timers (Example Code), swift use NSTimer in app background. target: self, selector: #selector(​timerCallBack), userInfo: nil, repeats: true) timer.fire() Background timers are a very usefool tool in one’s developer toolbox. Most of the time when we want to schedule a repeating unit of work we consult NSTimer.Problem is, NSTimer requires an active

how to use NSTimer background in swift?, My app runs music in background and i' use the timer in order to stop the sounds when i heard ios will stop your code running when its +3min active, so the  Today we go over how to create a timer in your app. Timer, previously know as NSTimer, is an object that you can use to run code repeatedly. By the end of this tutorial, you will know how to

Comments
  • stackoverflow.com/questions/8415870/…
  • Why do you need a timer to run in the background?
  • As stated, it was a quick port from a previous answer. I just ported the answer, tested the code, and it appeared to be working. I can clean up the example a bit and remove some junk code.
  • 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 @mediachicken
  • @王怡飞 Maybe it's time you step back and ask your self if that's really the best approach. It seems like a pretty hacky method. What exactly are you trying to achieve?
  • @mediachicken just a timer but I want it still running even I tap the home button.
  • @王怡飞 Ugh. So don't let the user play music on their device while your app is running in the background? Lol. And Apple approved an app for "music" background mode, even though it doesn't play music?!?
  • 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
  • Then learn how to do that. I did mention playing music as a legal background activity in my answer.
  • I suspect your app may be rejected from the app store if you do something like that. Please instead explain what it is that you feel you need to do in the background? By default, a suspended app is not something that the user cares about at that moment. It should be able to do what it needs to when the user starts using it again.
  • suppose i don't need any location or music. i just want to know server that my app is running in background continuesly so how can i do that i just want to call webservice every 10 sec when app is in background mode
  • Please add some comments about your answer.