如何将JSONSerialization响应转换为T或泛型?

时间:2019-05-30 05:49:24

标签: swift generics nsjsonserialization urlsession

我是泛型新手,并准备了可重用性的函数,但是我在最后一点停留在解析数据或JSON时如何在JSONSerialization之后将数据转换为T /泛型。

func getDataApi<T: Decodable>(Url: String, param: [String: Any]?, method: HTTPMethod, header: HTTPHeaders?, completion: @escaping (T) -> ()) {
    var request = URLRequest(url: URL(string: Url)!)
    request.httpMethod = method.rawValue
    for (keys,value) in header! {
        request.addValue(value, forHTTPHeaderField: keys)
    }

    do {
        request.httpBody = try? JSONSerialization.data(withJSONObject: param!, options: [])

        let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
            if let response = response {
                let nsHttpResponse = response as! HTTPURLResponse
                let statusCode = nsHttpResponse.statusCode
                print("statusCode: \(statusCode)")
            }
            if let error = error {
                print ("\(error)")
            }
            if let data = data {
                do {

                    let jsonResponse = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions())
                    print("data = \(jsonResponse)")

                    completion(jsonResponse as! T)
                } catch _ {
                    print ("Oops not good JSON formatted response")
                }
            }
        }
        task.resume()
    } catch _ {
        print ("Oops something happened buddy")
    }
}

我怎么称呼这个

ApiManager.shared.getDataApi(Url: Urls.registration, param: params, method: .post, header: headers) { (response: RegestrationModel) in
    print(response)               
}

我的问题就在这里

completion(jsonResponse as! T)

构建此文件时,它会在此处崩溃。

我得到这个错误:线程4:信号SIGABRT

0 个答案:

没有答案