title: Swift Stop Background Task
body: <p>I built my application with the management of the background task in this way:</p>
  
  <pre><code>var updateTimer: NSTimer?
  var backgroundTask: UIBackgroundTaskIdentifier = UIBackgroundTaskInvalid
  
  override func viewDidLoad() {
      super.viewDidLoad()
  
      // listen for UIApplicationDidEnterBackgroundNotification
  
      NSNotificationCenter.defaultCenter().addObserver(self,
      selector: "appDidEnterBackground:",
      name: UIApplicationDidEnterBackgroundNotification, object: nil)
  }
  
  func reinstateBackgroundTask() {
      if updateTimer != nil &amp;&amp; (backgroundTask == UIBackgroundTaskInvalid) {
          registerBackgroundTask()
      }
  }
  
  func registerBackgroundTask() {
      backgroundTask = UIApplication.sharedApplication().beginBackgroundTaskWithExpirationHandler {
          [unowned self] in
          self.endBackgroundTask()
      }
      assert(backgroundTask != UIBackgroundTaskInvalid)
  }
  
  func endBackgroundTask() {
      NSLog("Background task ended.")
      UIApplication.sharedApplication().endBackgroundTask(backgroundTask)
      backgroundTask = UIBackgroundTaskInvalid
  }
  
  func calculateNextNumber() {
      switch UIApplication.sharedApplication().applicationState {
      case .Active:
          break
      case .Background:
          NSLog("Background time remaining = %.1f seconds", UIApplication.sharedApplication().backgroundTimeRemaining)
      case .Inactive:
          break
      }
  }
  
  func appDidEnterBackground(notification:NSNotification) {
      updateTimer?.invalidate()
      updateTimer = nil
      if backgroundTask != UIBackgroundTaskInvalid {
          endBackgroundTask()
      }
  }
  </code></pre>
  
  <p>but I can not block the background timer . I would like to use the three minutes not continuously but fragmenting, for example using a 5 second intervals. I do not know if you can do , let me know if this is possible and how. thank you
  Edit:
  I certainly have not been clear. I can stop and resume the remaining time of the backgroundTimeRemaining ?
  example</p>
  
  <pre><code>if the backgroundTimeRemaining == 168.0 {
      endBackgroundTask()
  }
  </code></pre>
  
  <p>I have tried it, but it doesn't work !!!</p>