0

I'm building an app that only consume a Web Service. For that, I use a method dataTask (URLSession.shared.dataTask).

I'm not waiting for information, only a process is triggered with the next code:

let endPoint = "http://host/service

let url = URL(string: endPoint)

let task = URLSession.shared.dataTask(with: url!) {_, _, _ in

}
task.resume()

When the method dataTask executes, Xcode show me the error:

"Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value"

Is there a way to skip the return completionHandler (data, response, error)?

vadian
  • 274,689
  • 30
  • 353
  • 361

1 Answers1

1

A completion handler is needed, but does not have to be specified when creating the data task object. In that case, you must define a URLSessionDataDelegate that will handle the response.

"A URLSession object need not have a delegate. If no delegate is assigned, when you create tasks in that session, you must provide a completion handler block to obtain the data.

Completion handler blocks are primarily intended as an alternative to using a custom delegate. If you create a task using a method that takes a completion handler block, the delegate methods for response and data delivery are not called." (https://developer.apple.com/documentation/foundation/urlsessiondatadelegate).

As for the crash, it seems to be related to the force unwrapping (the ! symbol) used in the when declaring the task. You could use a guard condition to abort safely if this error is happening.

guard let url = URL(string: endPoint) else { return }

URLSession.shared.dataTask(with: url) {_, _, _ in
}.resume() 
folverap
  • 126
  • 3
  • Thank you @folverap I can resolve the issue. Is there a way to debug or check if the dataTask run? If I execute my WebService in browser or postman, that response OK, but when I try to execute in my code, nothing happens. – Victor Carmona Pale Mar 24 '20 at 16:38
  • You use the completion block(Data?, URLResponse?, Error?) for that. If Error is not nil, then the request failed. If it was successful, errir will be nil and your Data object should not be nil. – folverap Mar 28 '20 at 21:36