I am developing an app and I need to update data in my app every day. I decided to use Background Fetch. I am downloading the data from an API so I am using URLSession. Since no completion handlers are allowed in performFetchWithCompletionHandler
I am using delegate for that purpose. But my problem is that when I try to update the data when my app is not running the function didRecieve data
is not called. Am I doing something wrong or should I use something else to update my data every day from an API?
My code is below:
func createTask(url: String, id: String){
let accessKey = UserDataService().getCurrentUser().accessToken
let backgroundConfigObject = URLSessionConfiguration.background(withIdentifier: id + UUID().uuidString)
let backgroundSession = URLSession(configuration: backgroundConfigObject, delegate: self, delegateQueue: nil)
var request = URLRequest(url: URL(string: url)!)
request.setValue("Bearer \(accessKey!)", forHTTPHeaderField: "Authorization")
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpMethod = "GET"
let task = backgroundSession.dataTask(with: request)
task.resume()
print("task resumed")
}
This function gets called inside performFetchWithCompletionHandler
and creates new dataTask
but didRecieve data
is not called.
I also tried adding this code inside performFetchWithCompletionHandler
print("BG FETCH")
let url = "secret url"
var request = URLRequest(url: URL(string: url)!)
request.setValue("SOME KEY", forHTTPHeaderField: "Authorization")
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpMethod = "GET"
URLSession.shared.dataTask(with: request, completionHandler: { (data, response, error) in
print("DATA",data)
completionHandler(.newData)
}).resume()
Thank you for any suggestion!