My app uses web data. When running in the foreground, the following code works very nicely. (I've defined it in the view controller class but also in a separate Central.swift file. Same behavior.)
It also works during a background fetch, but only sporadically. It's not 100% reliable:
var urlString: String = "some website"
if let url = URL(string: urlString) {
var url = URL(string: urlString)
var request = URLRequest(url: url!)
request.httpMethod = "GET"
request.addValue("text/html", forHTTPHeaderField: "Content-Type")
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
print("The Error is \(error)")
if data != nil {
var return1 = NSString(data: data!, encoding: String.Encoding.utf8.rawValue) as! String
// Process the web data here
DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
var defaults: UserDefaults = UserDefaults.standard
defaults.set(myNumber, forKey: "myKey")
defaults.set(Date(), forKey: "myUpdate")
self.UILabel?.text = x
Central().someFunction()
// This function is defined in the class Central.swift. It uses data stored in user defaults.
// It sends a notification if the app state is inactive.
}
}
}
task.resume()
}
When it fails, it seems to be stuck just before the DispatchQueue statement. Sometimes everything inside the Dispatch will execute when I bring the app to the foreground, instead of executing in the background beforehand. When it works, the commands in Dispatch execute normally, including the sending of an an alert notification to the user that's called in the Central().someFunction. This tells the user that new data has arrived.
Should the Session be something besides URLSession.shared ? What else?
This is really making me nuts. As I write this, it just worked. But I know it often will not.
BTW, I do my testing with my iPhone 6, not iOS simulator. Part of my confusion is that printing to the console may fail even when the code seems to have otherwise worked.
PS: I add a print to line #08 above and get this on the console:
The Error is Optional(Error Domain=NSURLErrorDomain Code=-1001 "The request timed out." UserInfo={NSUnderlyingError=0x170052bd0 {Error Domain=kCFErrorDomainCFNetwork Code=-1001 "(null)" UserInfo={_kCFStreamErrorCodeKey=-2102, _kCFStreamErrorDomainKey=4}}, NSErrorFailingURLStringKey= some website, NSErrorFailingURLKey=some website, _kCFStreamErrorDomainKey=4, _kCFStreamErrorCodeKey=-2102, NSLocalizedDescription=The request timed out.})
A similar discussion is here: https://forums.developer.apple.com/thread/22032