How to pass parameter to a post API in swift

380 views Asked by At

I have a API with the parameters as given in the image.enter image description here

How to give these parameters in the swift code. I have tried the code this way, but it does not seem to work.

let header: HTTPHeaders = ["Content-Type":"application/json","x-token": self.usertoken!]
let parameters = [ "request_type" : "nanny_submit_exam",
                          "exam_id": self.examid!] as [String : Any]

        AF.upload(multipartFormData: { (multipartFormData) in

                          for (key, value) in parameters {
                             multipartFormData.append("\(value)".data(using: String.Encoding.utf8)!, withName: key as String)
                          }
            for i in 0..<(self.listData?.nanniBookingDetails.questionsData.count)!
                                             {
                                                multipartFormData.append(self.answers[i].data(using: String.Encoding.utf8)!, withName: "answers[i][\(1)]['answer']")
                                            }
              }, to: mainURL+URLS.custom.rawValue, usingThreshold: UInt64.init(), method: .post, headers: header).responseJSON { response in
  switch response.result {
                   case .success(let json):
                       print("Validation Successful",json)
                       if let res = json as? [String: Any]{
}
 case let .failure(error):
                                     // self.loadingview.isHidden = true
                                      print(error)
                                      self.showAlert(message: "No internet connection")
                                  }
                   
               }

This is throwing alamofire error Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(error: Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.})) which means the parameter passed is wrong. Could you tell me where i am wrong with these parameters.As it is working in the postman.

1

There are 1 answers

1
neprocker On

Select "Code" below the save button, you can select swift. This will give you the collection you need to pass as parameter