从 HttpSession post 返回响应数据

问题描述 投票:0回答:0

我创建了一个外部 HttpPOST.swift 文件来轻松处理 http 请求。它工作得很好,但是当我尝试将响应数据传递到字典时,我收到错误:

Cannot assign value of type 'Response' to type '[String : Any]'

你能告诉我为什么吗?谢谢!

HttpPOST.swift

import UIKit
public var asd = Dictionary<String, Any>()
func apiCall(){
    
    guard let url = URL(string: "http://192.168.1.71:3000/user/login")else{
        return
    }
    
    var request = URLRequest(url: url)
    // method, body, headers
    request.httpMethod = "POST"
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")
    let body: [String: AnyHashable] = [
        "username": "Alms",
        "password": "asd"
    ]
    request.httpBody = try? JSONSerialization.data(withJSONObject: body, options: .fragmentsAllowed)
    
    // make rqs
    let task = URLSession.shared.dataTask(with: request){ data, response, error in
        guard let data = data,error == nil else {
            return
        }
        
        do {
            let response = try JSONDecoder().decode(Response.self, from: data)
            asd = response;
            print("SUCCESS: \(response)")
        }
        
        catch {
            print(error)
        }
        
    }
    
    task.resume()
}

struct Response: Codable {
    var usernameError: String?;
    var passwordError: String?;
    var logOk: Bool?;
    var token: String?;
}
swift httpsession
© www.soinside.com 2019 - 2024. All rights reserved.