I have question regarding to iOS Background Tasks or Process. I have an application which should inform you by local notification every 15 minutes if you have new email -> if you do not have any, nothing happen.
I have found lot of tutorials for Swift 4, Swift 5 but only few should working on iOS 13 and new framework BackgroundTask. I tried all of them and I did not get the working solution (firstly I get errors because I tried it on Simulator, now I getting a message "Can't end a bg task..." - It seems to be bug in Xcode.) and app could not refresh because of no reason.
AppDelegate.swift
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
UNUserNotificationCenter.current().delegate = self
registerBackgroundTaks()
return true
}
func applicationDidEnterBackground(_ application: UIApplication) {
scheduleEmailFetcher()
}
//MARK: Register BackGround Tasks
private func registerBackgroundTaks() {
BGTaskScheduler.shared.register(forTaskWithIdentifier: "com.InformationSystem.emailFetch", using: nil) { task in
//This task is cast with processing request (BGProcessingTask)
self.setNotification()
self.handleEmailFetcher(task: task as! BGProcessingTask)
}
}
func cancelAllPandingBGTask() {
BGTaskScheduler.shared.cancelAllTaskRequests()
}
func handleEmailFetcher(task: BGProcessingTask) {
scheduleEmailFetcher() // Recall
task.expirationHandler = {
self.cancelAllPandingBGTask()
}
print("Handling BG Task!")
// GET Request to server and other logic here?
setNotification()
task.setTaskCompleted(success: true)
}
func scheduleEmailFetcher() {
let request = BGProcessingTaskRequest(identifier: "com.InformationSystem.emailFetch")
request.requiresNetworkConnectivity = true
request.requiresExternalPower = false
print("Scheduled")
request.earliestBeginDate = Date(timeIntervalSinceNow: 15 * 60)
do {
try BGTaskScheduler.shared.submit(request)
} catch {
print("Could not schedule email fetch: \(error)")
}
}
Is there anybody who can help me get rid of it?
Thanks a lot for help!