在 swift 4 中对编码类型的网络调用



我是 swift 的新手,也很困惑。如何为 post 方法编写通用网络方法以在 swift 4 中对结构类型的对象进行编码。正如我编写了一个方法,该方法采用登录类型的参数帖子,其中登录是可编码类型的结构。我需要使其通用化,而不是只接受登录类型。

通常,首先将会话对象注入此服务类。您还提供请求块和完成块。在您的情况下,您可以考虑使用泛型。

func doURLsessions(completionHandler: @escaping (SomeType?)->()) {
let session = URLSession(configuration: URLSessionConfiguration.default)
if let timeurl = URL(string: "https://www.quandl.com/api/v3/datasets/NSE/NIFTY_50.json?api_key=xMH7BiBu6s24LHCizug3") {
    (session.dataTask(with: timeurl, completionHandler: { (data, response, error) in
        if let error = error {
            print("Error: (error)")
        } else if let data = data {
            let jsonDecoder = JSONDecoder()
            let response = try? jsonDecoder.decode(YourCodableStruct.self, from: data)
            if (response?.data != nil) {
                //process data, call the completion handler.
            }
        }
    })).resume()
}

通常,每个终结点都有一个单独的函数,所有函数都在同一类中。

相关内容

最新更新