how to get the error code from dataTask working in background sessions?

My program is shown in following.

I want to get the dataTask session's error code working in background, but I haven't achieved it.

let config:URLSessionConfiguration = URLSessionConfiguration.background(withIdentifier: "abcd")
self.session = URLSession(configuration: config, delegate: nil, delegateQueue: nil)
let task: URLSessionDataTask = session!.dataTask(with: myRequest as URLRequest)
task.resume()

In the program above, there isn't any parameter with error information, so I rewrite it as following.

But when I run the following program, the exception error happens.

By the way, about the following program, it can be run successfully when URLSession is configured as normal session, but when URLSession is configured as background session as following, the exception error happens when it's run.

Anyone can give me some advice?

Thanks a lot!

let config:URLSessionConfiguration = URLSessionConfiguration.background(withIdentifier: "abcd")
self.session = URLSession(configuration: config, delegate: nil, delegateQueue: nil)
let task: URLSessionDataTask = session!.dataTask(with: myRequest as URLRequest) { (data, response, error) in
            if let response = response as? HTTPURLResponse {
                    NSLog("response.statusCode = \(response.statusCode)")
            }
       }
task.resume()
Answered by DTS Engineer in 715437022

Background sessions don’t support the URLSession convenience API. You have to use a session delegate to get information about tasks in such a session. For the details, see Downloading Files in the Background.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

Accepted Answer

Background sessions don’t support the URLSession convenience API. You have to use a session delegate to get information about tasks in such a session. For the details, see Downloading Files in the Background.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

Dear Eskimo

Thank for you very much!

I also noticed some other issue such as this one. I tried the same method with delegate, but I got the same result mentioned in the issue that I couldn't get any reponse or error information from "Delegate method urlSession(_:dataTask:didReceive:)".

It seems you have given some help for the issue above.

Could you please give me more detail advice?

Dear Eskimo

I have succeeded to get the information by setting URLSession delegate.

By the way, the reason I failed before is the delegate declaration in my program had some mistake.

Thank you very much!

how to get the error code from dataTask working in background sessions?
 
 
Q