将GET请求数据传递到iOS Swift中的POST请求

时间:2020-10-13 13:27:44

标签: ios swift api dictionary http-post

嗨,我在为POST请求获取正确的数据格式方面遇到了一些挑战。

我有两个功能,一个是执行GET请求,如下所示(我正在使用alamofire):

func performRequestRdw(dataURL: String, headers: HTTPHeaders) {
        
        AF.request(dataURL, method: .get, headers: headers).responseJSON { response in
            debugPrint(response)
            if let safeData = response.data {
                if let rdwVehicle = self.parseRdwJSON(rdwData: safeData) {
                    print("safeData is: \(safeData)")
                    self.delegate?.didUpdateRdwInfo(rdwData: rdwVehicle)
                    
                    self.performRequestAddVehicle(dataURL: self.addVehicleUrl, headers: headers, parameters: rdwVehicle)
                    
                }
            }
            
        }
    }


    func parseRdwJSON(rdwData: Data) -> RdwModel? {
        let decoder = JSONDecoder()
        do {
            let decodedData = try decoder.decode(RdwData.self, from: rdwData)
            print("plateNumber is: \(decodedData.plateNumber)")
            let hasBasicInsurance = decodedData.hasBasicInsurance
            let nextInspectionDate = decodedData.nextInspectionDate
            let platNumber = decodedData.plateNumber
            let brand = decodedData.vehicle.brand
            let model = decodedData.vehicle.model
            let orginalPrice = decodedData.originalPrice.amount
            let currency = decodedData.originalPrice.currency

            
            
            let rdwData = RdwModel(hasBasicInsurance: hasBasicInsurance, nextInspectionDate: nextInspectionDate, plateNumber: platNumber, brand: brand, model: model, currency: currency, amount: orginalPrice)
            
            do {
                let data = try JSONEncoder().encode(rdwData)
                print("data is: \(data)")
            } catch {
                print(error)
            }
            
            
            return rdwData
            
            
        }catch {
            delegate?.didFailWithError(error: error)
            print(">>>Error is \(error)")
            return nil
        }
    }

另一个是通过API发送数据的POST函数:

    func performRequestAddVehicle(dataURL: String, headers: HTTPHeaders, parameters: Parameters) {

        AF.request(dataURL, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers).responseJSON { response in
            debugPrint(response)
        }
    }

我在 self.performRequestAddVehicle(dataURL: self.addVehicleUrl, headers: headers, parameters: rdwVehicle)函数的performRequestRdw中出错。

它表示“ 无法将'RdwModel'类型的值转换为预期的参数类型'Parameters'(aka'Dictionary ')”

我的问题是:如何从GET请求转换正确的数据格式,然后在POST请求中使用它。参数POST请求询问的是字典。我找不到一种很好的方法。

非常感谢您的帮助;-)

0 个答案:

没有答案