title: Periodic background updates
body: <hr>
  
  <p>This question is an update to some outdated questions like:</p>
  
  <ul>
  <li><p><a href="https://stackoverflow.com/questions/37319143/how-to-call-function-after-every-1-hourswift-background-fetch-work-when-app/37319305">how to call function after every 1 hour?(Swift). Background fetch work when app is terminated?</a></p></li>
  <li><p><a href="https://stackoverflow.com/questions/37189277/sending-latitude-and-longitude-to-server-when-app-is-in-background?noredirect=1&amp;lq=1">Sending Latitude and Longitude to Server when app is in background</a></p></li>
  <li><p><a href="https://stackoverflow.com/questions/19042894/periodic-ios-background-location-updates?noredirect=1&amp;lq=1">Periodic iOS background location updates</a></p></li>
  <li><p>...</p></li>
  </ul>
  
  <hr>
  
  <p>I'm currently developing an simple mobile application for iOS by using <strong>Swift 4</strong>.</p>
  
  <p>It's a messenger app like <code>e.g. WhatsApp</code> and because new messages must be delivered instantly the application must be <strong>able to check for new messages for the Users via Json request</strong> every minute.</p>
  
  <pre><code>var backgroundTask: UIBackgroundTaskIdentifier = UIBackgroundTaskInvalid
  
  func registerBackgroundTask() {
      backgroundTask = UIApplication.shared.beginBackgroundTask { endBackgroundTask() }
      assert(backgroundTask != UIBackgroundTaskInvalid)
  }
  
  func endBackgroundTask() {
      print("Background task ended.")
      UIApplication.shared.endBackgroundTask(backgroundTask)
      backgroundTask = UIBackgroundTaskInvalid
  }
  </code></pre>
  
  <p><br></p>
  
  <p>Till now - when the app is in background-mode after about 2 minutes the app is terminating, the <code>getnewmessages-timer interval</code> is stopping and it prints out <code>"Background task ended"</code>.</p>
  
  <p><strong>How to use Swift to register an infinite-running timer</strong> (background-fetching) that calls the <strong>update messages function</strong>?</p>
  
  <blockquote>
    <p>iOS background fetch <strong>for</strong>: An app that downloads and process new content regularly --> My messenger app</p>
  </blockquote>