That is my NSURLSession code, basically I’m attempting to add a file to S3 utilizing HealthKit on a schedule within the background. I simply need to set up the app and this add course of ought to occur on a schedule day by day mechanically even when the app is within the background.
import UIKit
class AppDelegate: UIResponder, UIApplicationDelegate, URLSessionDelegate, URLSessionTaskDelegate {
var window: UIWindow?
var uploadTimer: Timer?
var backgroundSession: URLSession?
// Methodology to add information to S3 (No want for a file path)
@objc func uploadDataToS3() {
// Use your present perform to fetch and add the well being information
HealthStoreManager.shared.fetchAndUploadHealthData { success in
if success {
print("Knowledge uploaded efficiently!")
} else {
print("Didn't add information.")
}
}
}
func scheduleDailyUpload() {
let calendar = Calendar.present
let currentTime = Date()
var nextUploadTime = calendar.date(bySettingHour: 14, minute: 07, second: 0, of: currentTime)
if let nextTime = nextUploadTime, nextTime < currentTime {
nextUploadTime = calendar.date(byAdding: .day, worth: 1, to: nextTime)
}
if let nextUploadTime = nextUploadTime {
let timeInterval = nextUploadTime.timeIntervalSince(currentTime)
uploadTimer = Timer.scheduledTimer(timeInterval: timeInterval, goal: self, selector: #selector(uploadDataToS3), userInfo: nil, repeats: true)
}
}
// When the app is launched, schedule the duty
func applicationDidBecomeActive(_ utility: UIApplication) {
scheduleDailyUpload()
}
// Deal with when the app is distributed to the background
func applicationDidEnterBackground(_ utility: UIApplication) {
// In background, create a background session to deal with add job
let config = URLSessionConfiguration.background(withIdentifier: "com.yourApp.backgroundUpload")
backgroundSession = URLSession(configuration: config, delegate: self, delegateQueue: nil)
// We do not want a file path, so we simply set off your add perform
uploadDataToS3()
}
// Deal with when the app comes again to the foreground
func applicationWillEnterForeground(_ utility: UIApplication) {
scheduleDailyUpload()
}
// Deal with background add completion or failure
func urlSession(_ session: URLSession, job: URLSessionTask, didCompleteWithError error: Error?) {
if let error = error {
print("Background add failed with error: (error.localizedDescription)")
} else {
print("Background add accomplished efficiently.")
}
}
// Deal with the add progress (elective)
non-public func urlSession(_ session: URLSession, uploadTask: URLSessionUploadTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
print("Add progress: (totalBytesSent) / (totalBytesExpectedToSend) bytes despatched.")
}
// This methodology known as when the app is terminated and a background add job continues to be operating
func utility(_ utility: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: @escaping () -> Void) {
backgroundSession?.getTasksWithCompletionHandler { (_, _, uploadTasks) in
if uploadTasks.depend == 0 {
completionHandler() // When the add job is completed, name the completion handler
}
}
}
}
Now this works as meant when linked to XCode within the debugging mode. It uploads the file mechanically on the specified time even when the app is minimized and within the background. However as quickly as I kill the debugger, the app stops importing the file from the background.
Is one thing improper with the code or the way in which I’m implementing it?