Background Tasks in Swift: Utilizing Local Push Notifications
Written on
A background task in Swift refers to a system-initiated process that operates while your application is not in the foreground. These tasks play a vital role in ensuring your app functions smoothly, allowing for actions like API calls to refresh data or sending notifications. By utilizing background tasks, your application can offer important features and maintain an engaging user experience even when it's not actively displayed.
First Steps: Enable Background Task Capability
To set up background tasks in your Swift project, adhere to the following instructions:
- Launch Xcode and open your project in the project navigator.
- Click on your project at the top to access the settings.
- Navigate to the ‘Signing & Capabilities’ tab.
- Press the ‘+ Capability’ button to add a new capability.
- Type ‘Background Modes’ into the search bar to find the relevant capability.
- Enable the options for background fetch and background processing.
- Save your modifications.
Activating these background modes enables your app to execute tasks while in the background, keeping it responsive and current even when it's not in use.
Next Steps: Handling Key Components
You will need to address four essential components:
- Insert your identifier into the info.plist file.
- Register a handler for the background task.
- Add the task to the scheduler.
- Implement the task's execution.
Before coding, it's important to add a unique identifier in your Info.plist file:
<key>BGTaskSchedulerPermittedIdentifiers</key>
<array>
<string>your.background.task.identifier</string></array>
Starting with Code Implementation
To begin coding, first, import the BackgroundTasks framework at the top of the AppDelegate file:
import BackgroundTasks
Next, define a new string variable using the identifier you added to your Info.plist:
let taskId = "your.background.task.identifier"
Within the didFinishLaunchingWithOptions method, include the following code:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
BGTaskScheduler.shared.register(forTaskWithIdentifier: self.taskId, using: nil) { task in
guard let task = task as? BGProcessingTask else { return }
// Task implementation goes here
handleBackgroundTask(task: task)
}
return true
}
Before proceeding with the task itself, it's necessary to submit your background task request:
private func submitBackgroundTask() {
// Check for pending task requests
BGTaskScheduler.shared.getPendingTaskRequests { request in
print("(request.count) BGTask pending.")
guard request.isEmpty else { return }
// Create a new background task request
let request = BGProcessingTaskRequest(identifier: taskId)
request.requiresNetworkConnectivity = false
request.requiresExternalPower = false
request.earliestBeginDate = Date(timeIntervalSinceNow: 120) // Schedule next task in 2 minutes
do {
// Schedule the background task
try BGTaskScheduler.shared.submit(request)
} catch {
print("Unable to schedule background task: (error.localizedDescription)")}
}
}
Now that we have successfully registered our background task, we can begin implementing it.
For instance, we will create a local push notification within our background task:
func handleBackgroundTask(task: BGProcessingTask) {
// Execute background task work here (e.g., trigger local notifications)
scheduleNotification()
// Mark the task as complete
task.setTaskCompleted(success: true)
}
Creating the Notification Scheduler
Here’s how we can schedule the push notification:
func scheduleNotification() {
// Set up notification content
let content = UNMutableNotificationContent()
content.title = "Local Notification"
content.body = "This is a local notification example."
content.sound = .default
// Configure a trigger for the notification (every 2 minutes)
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 120, repeats: true)
// Create a request with a unique identifier
let request = UNNotificationRequest(identifier: "localNotification", content: content, trigger: trigger)
// Add the request to the notification center
UNUserNotificationCenter.current().add(request) { error in
if let error = error {
print("Error scheduling notification: (error.localizedDescription)")}
}
}
Note: Remember to request permission for local notifications. Call the following function within the didFinishLaunchingWithOptions method:
import UserNotifications
func requestPermission() {
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options: [.alert, .sound, .badge]) { (granted, error) in
if granted {
print("Permission granted for local notifications")} else {
if let error = error {
print("Error requesting permission: (error.localizedDescription)")} else {
print("Permission denied for local notifications")}
}
}
}
Conclusion
In summary, utilizing background tasks in Swift can greatly enhance the efficiency and responsiveness of your iOS applications. By adhering to the guidelines in this article, you can ensure a smooth user experience while maximizing the benefits of the background task system. As you implement these tasks into your Swift projects, stay informed about the latest iOS developments and consider your application's specific needs. Happy coding, and may your background tasks operate seamlessly!
Contact Information
If you have any questions or insights to share, or if you wish to connect, feel free to reach out to me on LinkedIn. You can find me at [Eslam Ali]. I'm always eager to engage in discussions and collaborations within the Swift community. I look forward to connecting with you!