簡體   English   中英

多參數字典(集合列表)如:[[String: Any]] 到 Alamofire 參數

[英]Multi parameters Dictionary (collection list) Like: [[String: Any]] to Alamofire Parameters

嗨,我正在嘗試為字典中名為“Dict”的 alamofire 參數提供...字典可以包含 3 個或 X 個項目。 我正在嘗試使用 FOR 循環將字典添加到另一組項目中,但是......它只顯示最后一個......似乎它覆蓋了前一個。 我嘗試了我所知道的一切......甚至嘗試使用 SwiftyJSON 框架......但 alamofire 只采用純字典類型。

    var Dict = [[String: Any]]()
    
    Dict.removeAll()
    
    for (index, value) in _SurveySubmitModel.enumerated() {
        print("Item \(index + 1): \(value)")
        
        let parameters: [String: Any] = [
            "ID": value.ID,
            "SurveyID": value.SurveyID,
            "QuestionID": value.QuestionID,
            "FilledBy": value.FilledBy,
            "Response": value.Response
        ]
        
        Dict.append(parameters)
        
    }
    
    print("Dict = \(Dict)")

好吧,我需要這樣的東西

 [{
  "ID": 0,
  "SurveyID": 25,
  "QuestionID": 28,
  "FilledBy": 7335,
  "Response": "1In the two weeks before you felt sick, did you:"
 },
 {
  "ID": 0,
  "SurveyID": 25,
  "QuestionID": 28,
  "FilledBy": 7335,
  "Response": "1In the two weeks before you felt sick, did you:"
 }
 ]

試試下面的代碼,我已經將[String: Any]修改為NSDictionary 也改變for循環。

var _SurveySubmitModel = [SurveySubmitModel]()

_SurveySubmitModel.append(SurveySubmitModel(ID: 0, SurveyID: 25, QuestionID: 28, FilledBy: 7335, Response: "1In the two weeks before you felt sick, did you:"))
_SurveySubmitModel.append(SurveySubmitModel(ID: 0, SurveyID: 25, QuestionID: 28, FilledBy: 7335, Response: "1In the two weeks before you felt sick, did you:"))
        
for survey in _SurveySubmitModel {
    
    let parameters: NSDictionary = [
        "ID": survey.ID,
        "SurveyID": survey.SurveyID,
        "QuestionID": survey.QuestionID,
        "FilledBy": survey.FilledBy,
        "Response": survey.Response
    ]
    
    Dict.append(parameters)
    
}
print("Dict == ", Dict)

輸出是

Dict ==  [{
    FilledBy = 7335;
    ID = 0;
    QuestionID = 28;
    Response = "1In the two weeks before you felt sick, did you:";
    SurveyID = 25;
}, {
    FilledBy = 7335;
    ID = 0;
    QuestionID = 28;
    Response = "1In the two weeks before you felt sick, did you:";
    SurveyID = 25;
}]

嘗試以下功能來調用 Web 服務

func postValues(requestParams: [[String: AnyObject]], urlString: String) {

    let url = URL(string: urlString)
    var request = URLRequest(url: url!)
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")
    request.httpMethod = "POST"
    request.httpBody = try! JSONSerialization.data(withJSONObject: requestParams, options: [])

    AF.request(request).responseJSON { (response) in
        switch response.result {
        case .success:
          //  print(response.result.value)
            break
        case .failure:
            print(response.error)
            break
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM