在swift 4中调用Encoding类型的网络

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了在swift 4中调用Encoding类型的网络相关的知识,希望对你有一定的参考价值。

我是一个快速和非常困惑的新手。如何编写一个通用的网络方法,用于在swift 4中编码struct类型的对象的post方法。我编写了一个方法,它接受类型为login的参数post,其中login是类型的结构可编码的。我需要将其推广而不是仅接受登录类型。

答案

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

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

对于每个端点,通常都有一个单独的函数,所有这些函数都在同一个类中。

以上是关于在swift 4中调用Encoding类型的网络的主要内容,如果未能解决你的问题,请参考以下文章

致命错误:在 Windows 中调用未定义的函数 mb_detect_encoding()

51nod1109(bfs)

@PropertySource(value={"file:conf/application.properties"},encoding = "utf-8")(代

51nod 1270 数组的最大代价

hdu6153 A Secret CCPC网络赛 51nod 1277 KMP

实验五 网络编程与安全