DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Containerize Gradle Apps and Deploy to Kubernetes With JKube Kubernetes Gradle Plugin
  • Deploying a Scala API on OpenShift With OpenShift Pipelines
  • Top 5 Gantt Chart Libraries for Vue.js
  • Building a Simple Todo App With Model Context Protocol (MCP)

Trending

  • Simpler Data Transfer Objects With Java Records
  • When Airflow Tasks Get Stuck in Queued: A Real-World Debugging Story
  • The Future of Java and AI: Coding in 2025
  • Distributed Consensus: Paxos vs. Raft and Modern Implementations

How to Update App Content With Background Tasks Using The Task Scheduler In iOS 13?

More efficiently manage your tasks in i0S13.

By 
Yuvrajsinh Vaghela user avatar
Yuvrajsinh Vaghela
·
Updated Jul. 24, 19 · Tutorial
Likes (3)
Comment
Save
Tweet
Share
34.8K Views

Join the DZone community and get the full member experience.

Join For Free

In this iOS tutorial, you’re going to see an example of how to use the new BackgroundTasks framework for fetching images in the background while the phone is in idle mode.

Last month at WWDC Developer Conference 2019, Apple released the latest iOS 13 with a huge list of new features and functionalities. It was the second major revisions of the OS. It is now being used on more than one billion iOS devices worldwide. 

The most significant thing that Apple has made in this update is Optimized Trend. Originally launched in iOS 12, Optimized Trend has made iOS 13 faster and more efficient. The app updating time has been improved, while the app launching time has become two times as fast when compared to the previous iteration. The app download size has also been reduced to half.

Here’s a list of some of the important features brought in iOS 13:

  • Dark Mode.
  • Revamped Photos app.
  • Sign In with Apple.
  • HomeKit Secure Video.
  • Name and image in Messages.
  • Swiping keyboard.
  • Multi-user HomePod.
  • All-new Reminders app.
  • Memoji and stickers.
  • Smarter, smoother Siri voice assistance.

In terms of technical functionalities, Apple has introduced:

  • Advances in contextual action menus in iOS, macOS, and iPadOS.
  • UIWindowScene API and multitasking in iPadOS.
  • AI/ML functionalities like image and speech saliency, word embeddings, sound analysis, text catalogue and recognition, image similarity and classification, on-device speech, Face capture quality, sentiment classification.
  • Conversational shortcuts in Siri for apps.
  • New BackgroundTasks Framework.

BackgroundTasks Framework

This new framework is used for deferrable tasks that are better done in the background such as cleaning a database, updating a machine learning model, updating the displayed data for an app. This makes efficient use of processing time and power.

BackgroundTasks Framework has two main task requests under BGTaskScheduler:

  1. BGAppRefreshTaskRequest: This is a request to launch an app in the background to execute a short refresh task.
  2. BGProcessingTaskRequest: This is a request to launch an app in the background and execute a process that takes a longer time to complete.

BackgroundTasks can be used to perform various activities like database cleaning, uploading pictures to a server, syncing pictures in other devices, and many more.

In this iOS tutorial, we are going to take the iOS background task example of fetching the latest count of added images in the image gallery.

Implementing BackgroundTasks Framework in Your Project

1. Create a new project using XCODE 11.

Create a new Xcode project

Create a new Xcode project


2. Select “Single View App” in the iOS section and enter the project name. (We have kept the project name as “SOBackgroundTask”.)

enter the project name.

Enter project name


project properties

Project properties


3. Go to SoBackgroundTask Target, click on “Signing & Capabilities”, and then click on “+ Capability”.


adjust capabilities

Adjust capabilities



4. Double-tap “Background Modes”.

set background modes

Set background modes



5. Select “Background Fetch” and “Background Processing” from all background tasks.

set background modes

Set background modes



6. Add “BGTaskSchedulerPermittedIdentifiers” key in info.plist and add a task identifier array.

add task identifier

Add task identifier


Note: The system only runs the tasks registered with identifiers on a whitelist of task identifiers.

7. Import BackgroundTasks in AppDelegate.swift.

8. Create registerBackgroundTaks() method with identifier (use the same identifier we used in info.plist) and call it from Application:didFinishLaunchingWithOptions

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

registerBackgroundTaks()
return true
}

//MARK: Register BackGround Tasks
private func registerBackgroundTaks() {

BGTaskScheduler.shared.register(forTaskWithIdentifier: "com.SO.imagefetcher", using: nil) { task in
//This task is cast with processing request (BGProcessingTask)
self.scheduleLocalNotification()
self.handleImageFetcherTask(task: task as! BGProcessingTask)
}

BGTaskScheduler.shared.register(forTaskWithIdentifier: "com.SO.apprefresh", using: nil) { task in
//This task is cast with processing request (BGAppRefreshTask)
self.scheduleLocalNotification()
self.handleAppRefreshTask(task: task as! BGAppRefreshTask)
}
}


9. Create scheduleImagefetcher() and scheduleAppRefresh() method for fetching images from the gallery and refresh app once image fetch is completed. These methods are called from applicationDidEnterBackground.

func applicationDidEnterBackground(_ application: UIApplication) {
scheduleAppRefresh()
scheduleImagefetcher()
}

func scheduleImagefetcher() {
let request = BGProcessingTaskRequest(identifier: "com.SO.imagefetcher")
request.requiresNetworkConnectivity = false // Need to true if your task need to network process. Defaults to false.
request.requiresExternalPower = false
//If we keep requiredExternalPower = true then it required device is connected to external power.

request.earliestBeginDate = Date(timeIntervalSinceNow: 1 * 60) // fetch Image Count after 1 minute.
//Note :: EarliestBeginDate should not be set to too far into the future.
do {
try BGTaskScheduler.shared.submit(request)
} catch {
print("Could not schedule image fetch: \(error)")
}
}

func scheduleAppRefresh() {
let request = BGAppRefreshTaskRequest(identifier: "com.SO.apprefresh")
request.earliestBeginDate = Date(timeIntervalSinceNow: 2 * 60) // App Refresh after 2 minute.
//Note :: EarliestBeginDate should not be set to too far into the future.
do {
try BGTaskScheduler.shared.submit(request)
} catch {
print("Could not schedule app refresh: \(error)")
}
}


Note: You need to cancel pending background tasks if any, otherwise it will display error code=2.

To cancel the pending background task, we call the below method before scheduling a new task.

func cancelAllPendingBGTask() {
BGTaskScheduler.shared.cancelAllTaskRequests()
}


Note: iOS background task time limit is 30 seconds; the policy is still the same.

Conclusion

We hope this iOS tutorial has helped you to understand how BackgroundTasks Framework works. You can get the source code by referring to the github demo.

Here, we took only one example of fetching images in the background, there are various tasks for which we can use this framework.

Let us know if you have any suggestions or queries in this tutorial or any questions regarding iPhone app development.

app Task (computing)

Opinions expressed by DZone contributors are their own.

Related

  • Containerize Gradle Apps and Deploy to Kubernetes With JKube Kubernetes Gradle Plugin
  • Deploying a Scala API on OpenShift With OpenShift Pipelines
  • Top 5 Gantt Chart Libraries for Vue.js
  • Building a Simple Todo App With Model Context Protocol (MCP)

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!