-使用完成URLRequest的函数调用-JSON

时间:2019-02-10 11:51:54

标签: json swift urlrequest completion

我确实读了很多关于完成处理程序的函数,但是现在我有一个问题,如何以正确的方式调用此函数(downloadJSON)。我必须在函数中给出哪些参数,并在我自己的类(调用函数的地方)中处理结果数据(json)。

这是David Tran的代码。嗨,我制作了许多很棒的教程,但是在代码中没有调用此函数。

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()
}

1 个答案:

答案 0 :(得分:0)

让Xcode帮助您。键入downlo并按回车键。 Xcode完成功能

enter image description here

再次按回车键,您将获得参数

enter image description here

例如,您必须用参数名称替换占位符

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

注意:

您的代码中存在致命的类型不匹配错误:JSONSerialization行的结果为[String:Any],但是完成处理程序的第一个参数为JSON