-0.4 C
New York
Saturday, February 22, 2025

ios – NSURLSession works as supposed when in debugging, however not when disconnected


That is my NSURLSession code, primarily I’m making an attempt to add a file to S3 utilizing HealthKit on a schedule within the background. I simply wish to set up the app and this add course of ought to occur on a schedule every day robotically 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?


    // Technique to add knowledge to S3 (No want for a file path)

    @objc func uploadDataToS3() {
        // Use your present operate to fetch and add the well being knowledge
        HealthStoreManager.shared.fetchAndUploadHealthData { success in
            if success {
                print("Information uploaded efficiently!")
            } else {
                print("Did not add knowledge.")
            }
        }
    }


    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 process
        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 operate
        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, process: 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 (non-compulsory)
    personal func urlSession(_ session: URLSession, uploadTask: URLSessionUploadTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
        print("Add progress: (totalBytesSent) / (totalBytesExpectedToSend) bytes despatched.")

    }

    
    // This methodology is named when the app is terminated and a background add process continues to be working

    func utility(_ utility: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: @escaping () -> Void) {
        backgroundSession?.getTasksWithCompletionHandler { (_, _, uploadTasks) in
            if uploadTasks.rely == 0 {
                completionHandler() // When the add process is finished, name the completion handler
            }
        }
    }
}

Now this works as supposed when related to XCode within the debugging mode. It uploads the file robotically 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 flawed with the code or the way in which I’m implementing it?

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles