简体   繁体   中英

Swiftui Task not running in Background task

I've configured background tasks successfully on my app where a function would directly call a URL and process the data but I've recently changed this so that the function calls the URL, saves to documentsDirectory then processes the data. Since I've updated this my background tasks no longer fire.

I've tried wrapping the functions in a Task after a suggestion on a previous question here but I can't get the Background Task to fire/complete fully. Sometimes it will just print run the print, other times it will just re-schedule the next update and sometimes it will print & schedule but the task never seems to run. Any help would be much appreciated. Thanks!

Update 27/06: I've done some more troubleshooting on this since posting and it looks like the issue isn't with the task running but it is the app not handling let (url, response) = try await session.download(for: request) within the function in the background task.

This functions as expected within the app, but fails to complete when its a background task. Are there any additional steps or config changes needed to have this run as a background task? Cheers

BG Processing Task:

func handleAppRefresh(task: BGProcessingTask) {
    //Schedules another refresh
    scheduleAppRefresh()
        Task.detached {
            do {
                print("BGTask fired")
                let events = try await BGloadCSV(from: "Eventtest")
                
                print(events)
            } catch {
                print(error)
            }
        }
    print("handleAppRefresh fired")
}

Function to run:

func BGloadCSV(from csvName: String) async throws -> [CSVEvent] {
   var csvToStruct = [CSVEvent]()

   // Creates destination filepath & filename
   let documentsUrl:URL =  (FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first as URL?)!
   let destinationFileUrl = documentsUrl.appendingPathComponent("testcsv.csv")

   //Create URL to the source file to be downloaded
   let fileURL = URL(string: "https://example.com/testcsv.csv")!

   let sessionConfig = URLSessionConfiguration.default
   let session = URLSession(configuration: sessionConfig)

   let request = URLRequest(url:fileURL)

   let (url, response) = try await session.download(for: request)

   if let statusCode = (response as? HTTPURLResponse)?.statusCode {
    print("File downloaded Successfully. Response: \(statusCode)")
    }
   let _ = try FileManager.default.replaceItemAt(destinationFileUrl, withItemAt: url)
   let data = readCSV(inputFile: "testcsv.csv")

   var rows = data.components(separatedBy: "\n")

   rows.removeFirst()

   // Iterates through each row and sets values
   for row in rows {
       let csvColumns = row.components(separatedBy: ",")
       let csveventStruct = CSVEvent.init(raw: csvColumns)
       csvToStruct.append(csveventStruct)
    }
   print("LoadCSV has run and created testcsv.csv")

   pullData(events: csvToStruct)
   return csvToStruct
  }

I was able to re-create the URLSession into a background task with help from this article & Sample project provided.

https://www.ralfebert.com/ios-examples/networking/urlsession-background-downloads/

Hopefully it helps someone else in the future.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM