- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to run a timer in background within your iOS app
If you wish to run a timer in background within your iOS Application, Apple provides beginBackgroundTaskWithExpirationHandler method, you can read more about the same https://developer.apple.com/documentation/uikit/uiapplication/1623031-beginbackgroundtaskwithexpiration.
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 Application → Let’s name is BackgroundTimer.
Step 2 − Open AppDelegate.swift and under method applicationDidEnterBackground write the below code.
backgroundTaskIdentifier = UIApplication.shared.beginBackgroundTask(expirationHandler: { UIApplication.shared.endBackgroundTask(self.backgroundTaskIdentifier!) }) _ = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.doSomething), userInfo: nil, repeats: true)
Step 3 − Write new function doSomething()
@objc func doSomething() { print("I'm running") }
Finally your code should look like below
func applicationDidEnterBackground(_ application: UIApplication) { backgroundTaskIdentifier = UIApplication.shared.beginBackgroundTask(expirationHandler: { UIApplication.shared.endBackgroundTask(self.backgroundTaskIdentifier!) }) _ = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.doSomething), userInfo: nil, repeats: true) } @objc func doSomething() { print("I'm running") }
Run the application
Here we are printing “I’m running” when the application goes to background. When the app goes in background “I’m running” will start printing on the console. Tap the home button and test. However you can run your timer maximum for 3 minutes when your app is in background as specified in Apple documentation and tested.
While running this application, make the application in background and wait for 3 minutes you’ll see after 3 minutes “I’m running” won’t print. Now bring application to foreground and you will notice “I’m running” started printing.