Below is my code. Basically, I have a weather app. I wanted to Write a swift code, where I will use BGTaskScheduler to schedule a background task every minute.
The background task will set a local notification using UserNotifications.
The task will first call a function named getWeather
which will return the weather condition.
Set the weather condition as a notification description. And the notification title will be the timestamp. The registerBackgroundTask()
function is called from AppDelegate after granting notification from didFinishLaunchWithOptions
. Even if you cannot provide solution, telling me how to debug if the background task is set properly And how to debug if the notification is set properly will help too.
func registerBackgroundTask() {
let taskIdentifier = "net.tazwar.abohaoa"
BGTaskScheduler.shared.register(forTaskWithIdentifier: taskIdentifier, using: nil) { task in
self.handleBackgroundTask(task: task as! BGProcessingTask)
}
// Schedule the background task to run every minute
let request = BGProcessingTaskRequest(identifier: taskIdentifier)
request.requiresNetworkConnectivity = false
request.requiresExternalPower = false
do {
try BGTaskScheduler.shared.submit(request)
} catch {
print("Unable to schedule background task: \(error.localizedDescription)")
}
}
func handleBackgroundTask(task: BGProcessingTask) {
// Fetch weather condition
let weatherCondition = getWeather()
// Create a notification content
let content = UNMutableNotificationContent()
content.title = DateFormatter.localizedString(from: Date(), dateStyle: .medium, timeStyle: .short)
content.body = weatherCondition
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 1, repeats: false)
let request = UNNotificationRequest(identifier: "weatherNotification", content: content, trigger: trigger)
// Add the notification request to the notification center
UNUserNotificationCenter.current().add(request) { error in
if let error = error {
print("Failed to add notification request: \(error.localizedDescription)")
}
}
task.setTaskCompleted(success: true)
scheduleNextBackgroundTask()
task.expirationHandler = {}
}
func scheduleNextBackgroundTask() {
let taskIdentifier = "net.tazwar.abohaoa"
let request = BGProcessingTaskRequest(identifier: taskIdentifier)
request.requiresNetworkConnectivity = false
request.requiresExternalPower = false
// Schedule the background task to run every minute
let nextFireDate = Date(timeIntervalSinceNow: 60)
request.earliestBeginDate = nextFireDate
do {
try BGTaskScheduler.shared.submit(request)
} catch {
print("Unable to reschedule background task: \(error.localizedDescription)")
}
}
func getWeather() -> String {
return "Sunny"
}