0

Pass array of string in parameter request - swift 5. I want to send an array in a parameter from an alamofire request.

This is the request on Postman:

This is my solution:

var Token : String?
       var  tasksMO = [NSManagedObject]()
       let request = NSFetchRequest<NSFetchRequestResult>(entityName: "ConfirmActivationEntity")
       do {
           let results = try pe.context.fetch(request)
           tasksMO = results as! [NSManagedObject]
           for taskmo in tasksMO {
               Token = (taskmo.value(forKey: "access_token")  as! String )
           }
           print("assbil")
       } catch {
           print("fild")
       }
 print(" Token :\(Token!)")
let levels  : [String]  = ["+972569431827","+972598110437","+972592923343","3555656","00970567163651","258258"]

let paramsJSON = JSON(levels)
debugPrint(paramsJSON)
let parameters : [String : Any] = ["contacts":paramsJSON,"platform":2]


 let headers : HTTPHeaders = ["Authorization":"Bearer \(Token!)","Accept-Language" : Locale.current.languageCode ?? "ar", "Content-Type" : "application/x-www-form-urlencoded","Accept" : "application/json"]

guard let url = URL(string: "\(UrlApi.url)\(UrlApi.contactsPost)") else { return }

   sdLoader.startAnimating(atView: self.view)
   Alamofire.request(url, method: .post, parameters: parameters, headers: headers).responseJSON { response in
     if let error = response.error {
           print(error)
           return
       }

       if let status = response.response?.statusCode {
        print(status)
        print(response.result.value!)
         switch(status){
           case 200:

        self.sdLoader.stopAnimation()
         do{
              let decoder = JSONDecoder()
              let userResultDec = try decoder.decode(ContactsJSON.self, from: response.data!)
              decoder.keyDecodingStrategy = .convertFromSnakeCase
               if userResultDec.status == true {

                print(userResultDec.items)

               } else if userResultDec.status == false {
                   self.showAlert(title: "رسالة", message: "هناك خطا بالمعلومات المدخلة", style: .alert)
           }


          }  catch let parsingError {
               print("Error", parsingError)
               MessageBox.Show(Message: " \(parsingError) , خطأ في السيرفير ", MyVC: self)
          }
           case 401 :
            self.sdLoader.stopAnimation()
              print("error with response status: \(status)")
              print("خطأ في السيرفير")
              MessageBox.Show(Message: "error with response status: \(status) , خطأ في السيرفير ", MyVC: self)
           case 404 :
            self.sdLoader.stopAnimation()
              print("error with response status: \(status)")
              print("خطأ في السيرفير")
              MessageBox.Show(Message: "error with response status: \(status) , خطأ في السيرفير ", MyVC: self)

         case 500:
              MessageBox.Show(Message: "error with response status: \(status) , خطأ في السيرفير ", MyVC: self)
            default:
             print("Error")

           }
       }
    }

The problem is: The items in the array do not appear in the reference response from the server

I am using the Alamofire pod and the SwiftyJson pod with iOS 13, Swift 5, and Xcode 11.

3 Answers 3

1

Something is wrong with application/x-www-form-urlencoded conversations in Alamofire/Swift. It does work in Postman way. Postman automatically converts your array but swift does not.

struct ArrayEncoding: ParameterEncoding {
  func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
    var request = try URLEncoding().encode(urlRequest, with: parameters)
    request.url = URL(string: request.url!.absoluteString.replacingOccurrences(of: "%5B%5D=", with: "="))
    return request
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

How to use it in the REQUEST ??
0

Please try this example :

var apiRequest = URLRequest(url: url)
apiRequest.httpMethod = "POST"
apiRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")

let levels = ["+972569431827","+972598110437","+972592923343","3555656","00970567163651","258258"]

apiRequest.httpBody = try! JSONSerialization.data(withJSONObject: values)

Alamofire.request(apiRequest)
    .responseJSON { response in

        switch response.result {
        case .failure(let error):
            print(error)

            if let data = response.data, let responseStr = String(data: data, encoding: .utf8) {
                print(responseStr)
            }
        case .success(let responseValue):
            print(responseValue)
        }
}

Comments

0

This is how I make the request post by sending an array: (Alamofire v5)

let apiInputs = [
    "input1": "example1",    
    "input2": "example2",
    "input3": "example3",
    "inputN": "exampleN",
]

AF.upload(multipartFormData: { multipartFormData in
    for (key, value) in apiInputs {
        multipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)                                        } // End for multipart form data.
        }, to: "https://example.com/api")
    .responseJSON { response in
        debugPrint(response)
}

I leave you the official documentation:

Alamofire/MultipartFormData

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.