简体   繁体   English

Swiftui 任务未在后台任务中运行

[英]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.我已经在我的应用程序上成功配置了后台任务,其中一个函数将直接调用 URL 并处理数据,但我最近更改了这一点,以便函数调用 URL,保存到文档目录,然后处理数据。 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.在对上一个问题提出建议后,我尝试将函数包装在Task中,但我无法让后台任务完全触发/完成。 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. 27/06 更新:自发布以来,我对此进行了更多故障排除,看起来问题不在于任务正在运行,而是应用程序未处理let (url, response) = try await session.download(for: request)在后台任务中的函数内。

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: BG处理任务:

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.在本文和提供的示例项目的帮助下,我能够将 URLSession 重新创建为后台任务。

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

Hopefully it helps someone else in the future.希望它在未来对其他人有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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