Search code examples
jsonswifturlrequestcompletion

-- function-call with completion URLRequest - JSON


i did read a lot about functions with completion-handler, but now i have a problem how to call this function (downloadJSON) in the correct way. Which parameters do i have to give in the function and handle the result-data (json) in my own class, where the function was called.

This is the code from David Tran. Hi makes wonderful tutorials, but in the code there is no call of this function.

let request: URLRequest
lazy var configuration: URLSessionConfiguration = URLSessionConfiguration.default
lazy var session: URLSession = URLSession(configuration: self.configuration)

typealias JSONHandler = (JSON?, HTTPURLResponse?, Error?) -> Void

func downloadJSON(completion: @escaping JSONHandler)
{
    let dataTask = session.dataTask(with: self.request) { (data, response, error) in
        // OFF THE MAIN THREAD
        // Error: missing http response
        guard let httpResponse = response as? HTTPURLResponse else {
            let userInfo = [NSLocalizedDescriptionKey : NSLocalizedString("Missing HTTP Response", comment: "")]
            let error = NSError(domain: DANetworkingErrorDomain, code: MissingHTTPResponseError, userInfo: userInfo)
            completion(nil, nil, error as Error)
            return
        }

        if data == nil {
            if let error = error {
                completion(nil, httpResponse, error)
            }
        } else {
            switch httpResponse.statusCode {
            case 200:
                // OK parse JSON into Foundation objects (array, dictionary..)
                do {
                    let json = try JSONSerialization.jsonObject(with: data!, options: []) as? [String : Any]
                    completion(json, httpResponse, nil)
                } catch let error as NSError {
                    completion(nil, httpResponse, error)
                }
            default:
                print("Received HTTP response code: \(httpResponse.statusCode) - was not handled in NetworkProcessing.swift")
            }
        }
    }

    dataTask.resume()
}

Solution

  • Let Xcode help you. Type downlo and press return. Xcode completes the function

    enter image description here

    Press return again and you get the parameters

    enter image description here

    You have to replace the placeholders with parameter names for example

    downloadJSON { (json, response, error) in
         if let error = error {
             print(error)
         } else if let json = json {
             print(json)
         }
    }
    

    Note:

    There is a fatal type mismatch error in your code: The result of the JSONSerialization line is [String:Any] but the first parameter of the completion handler is JSON