如何在 Swift 4 中将 Encodable 或 Decodable 作为参数传递? [英] How to pass Encodable or Decodable as parameter in Swift 4?

查看:51
本文介绍了如何在 Swift 4 中将 Encodable 或 Decodable 作为参数传递?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习 JSONParsing.我跟着教程,我得到的是这样的:

I am learning JSONParsing. I followed tutorials and what I got is this:

    guard let url = URL(string: "http://localhost/test-api/public/api/register") else { return }

    var request  = URLRequest(url: url)

    request.httpMethod = "POST"

    let newUser = User.init(name: self.collectionTF[0].text, email: self.collectionTF[1].text, password: self.collectionTF[2].text)

    do {

        let jsonBody = try JSONEncoder().encode(newUser)

        request.httpBody = jsonBody

    } catch { }

    URLSession.shared.dataTask(with: request) { (data, response, error) in

        guard let data = data else { return }

        do {

            let json = try JSONSerialization.jsonObject(with: data) as? [String:Any]

            print(json!)

            DispatchQueue.main.async {

            if json!["status"] as! Int == 200
            {
                GeneralHelper.shared.keepLoggedIn()

                NavigationHelper.shared.moveToHome(fromVC: self)
            }

            }

        } catch { print(error.localizedDescription)}

        }.resume()

好的,这就是我为注册所做的.现在,我想创建一个 Helper,它将对 @escaping 做同样的事情,因为我们都需要解析的 JSON 作为回报.

Ok, this is what I have done for register. Now, I want to create a Helper, which will do the same thing with @escaping as I we all need the parsed JSON in return.

所以,我将 endPoint 作为字符串传递,然后尝试传递这个 newUser,它是一个 Encodable,它可以是一个 Decodable将来也一样,但它会引发错误无法使用类型为(Codable)"的参数列表调用encode".任何人都可以帮忙吗?而且,通过在 JSONParsing 中多次调用此函数,这样是否更好?

So, I am passing the endPoint as String and then trying to pass this newUser which is a Encodable, it can be a Decodable as well in future, but it throws an error Cannot invoke 'encode' with an argument list of type '(Codable)'. Can anyone please help? And, is it better this way, by calling this function multiple times when it comes to JSONParsing?

- 所以,我现在正在使用 networkRequestfunction,这是我所做的.

- So, I am now using the networkRequestfunction and here is what I have done.

 let newData = User.init(name: "Rob", email: "abc@gmail.com", password: "12345678")

ApiHelper.sharedInstance.networkRequest_Post(urlString: "register", header: nil, encodingData: newData) { (response: User, urlRes, error) in
        <#code#> }

现在,它给了我这个错误:Cannot convert type '(User, _, _) ->()' 到预期的参数类型 '(_?, HTTPURLResponse?, Error?) ->()'.有什么帮助吗?

Now, it gives me this error: Cannot convert value of type '(User, _, _) -> ()' to expected argument type '(_?, HTTPURLResponse?, Error?) -> ()'. Any help?

推荐答案

我在我的项目中使用了相同的功能

I have used the same functionality in my project

希望下面的代码会有所帮助

Hope the below code will help

    func networkRequest_Post<T: Decodable, Q: Encodable>(urlString: String,header:[String:String]?,encodingData: Q,completion: @escaping (T?, HTTPURLResponse?, Error?) -> ()) {

    guard let url = URL(string: urlString) else { return }
    let config = URLSessionConfiguration.default
    config.timeoutIntervalForRequest = 300.0
    config.timeoutIntervalForResource = 300.0
    if header != nil{
        config.httpAdditionalHeaders = header
    }
    let session = URLSession(configuration: config)
    var request = URLRequest(url: url)
    request.httpMethod = "POST"
    do {
        let jsonBody = try JSONEncoder().encode(encodingData)
        request.httpBody = jsonBody
    } catch {}
    let task = session.dataTask(with: request) { (data,response, err) in

        if let response = response {
            print(response)
        }
        if let err = err {
            print("Failed to fetch data:", err.localizedDescription, "Error Description\(err)")
            return
        }
        guard let data = data else { return }
        do {
            print(String(data: data, encoding: String.Encoding.utf8) as Any)
            let dataReceived = try JSONDecoder().decode(T.self, from: data)
                completion(dataReceived,response as? HTTPURLResponse,err)
        } catch let jsonErr {
            print("Failed to serialize json:", jsonErr, jsonErr.localizedDescription)
            completion( nil,response as? HTTPURLResponse,jsonErr)
        }
    }
    task.resume()
}

使用 -

         let newdata = User(name: "Abhi", email: "jhjhj@jhj.co", password: "123hguhj")
    networkRequest_Post(urlString: "YOUR_URL", header: nil, encodingData: newdata) { (RESPONSE_DATA:User?, URL_RESPONSE, ERROR) in
        // Do your network work here
    }

    struct User : Codable {
      var name: String?
      var email: String?
      var password: String?
    }

这篇关于如何在 Swift 4 中将 Encodable 或 Decodable 作为参数传递?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆