Swift iOS app development journal: URLSession.shared.DataTask convenience function

Today I wrote a small feature that allows the app to send out user-typed scores. I'm not going to talk about the details.

The main thing I would like to document is the implementation of the URLSession data task.

Swift UI uses the MVVM concept, where the model is responsible for handling all the handlings related to the data. in the case of this part of my implementation, the model has a struct that is responsible for the communication with the server, and a viewmodel class that is responsible for linking the results with the real view interface.

One of the most commonly used is URLSession.shared.DataTask, we will make a URLRequest for it, and then use URLSession.shared.dataTask(with: request, completionHandler: {} This function sends the request out, and the completion handler code often has to do some processing on the result of the web request, for example, if there is an error, we have to change some variables to make the view responsive, or if we receive the returned data, we have to do some processing on the returned data. or to handle the returned data when we receive the result. If we need to change some variables, it's usually very troublesome in struct, because usually the completion handler can't mutate the variables in struct, and in fact the completion handler should be escaping.

So it's easier to write this common action as a function and then pass the escaping handler in.

private func resumeDataTask(withRequest request: URLRequest, completion: @escaping (Result) -> Void) {
        let task = URLSession.shared.dataTask(with: request, completionHandler: {(data, response, error) -> Void in

           if let error = error {
               completion(.failure(error))
               print(error)
               print(error))
           }
           else if let data = data {
               completion(.success(data))
           completion(.success(data)))
       })

       task.resume()
    }

This code consists of making the URL task and sending it out. We can take two inputs, one is the finished URLRequest, and the completion handler is also passed in as a parameter. After the result is returned, we call the completion handler to return the result to him. This is the concept of a callback. Usually the completion handler is passed in from the function that initiates the entire action (which is ultimately linked to the function trigger that sends the URLRequest), which is usually from the ViewModel, i.e., a class. This function is usually from the ViewModel, which is a class, so it can save us a lot of data handling problems.


Thank you for reading this post. If you like my post, please follow up withFacebook Fan Specialist,Twitter,IGThe

Leave a ReplyCancel reply