-1

How can i post array of json objects with alamofire in swift?

my final data (which i want to post) looks like:

temp = [{
        "time": 1,
        "score": 20,
        "status": true,
        "answer": 456
    },
    {
        "time": 0,
        "score": 0,
        "status": false,
        "answer": 234
    },
    {
        "time": 0,
        "score": 20,
        "status": true,
        "answer": 123
    }
]

i got hint that i have to create custom parameter encoding but i am confused how can i do that. Someone please help me.

my current code looks like
let parameters: Parameters = [
    "answers": temp,
    "challenge_date": "2019-03-01"
]

Alamofire.request("...url", method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers)
    .responseJSON {
        response in

            if
        let status = response.response ? .statusCode {
            let classFinal: JSON = JSON(response.result.value!)

            if (status > 199 && status < 300) {
                self.dismiss(animated: true)
            } else {


            }
        }

    }
6
  • I guess temp is your array. Any errors that you are facing with this? Commented Mar 1, 2019 at 10:47
  • you need to send temp in the format of array & dict. See carefully, treat [ ... ] as array and { ... } as dict. Now set answers value with this. NOTE Your post req params data is always be in array and dict not json. Commented Mar 1, 2019 at 10:52
  • @GaneshSomani "JSON parse error - No JSON object could be decoded" Commented Mar 1, 2019 at 10:52
  • How is your Parameters class implemented. That is the source of your error. Commented Mar 1, 2019 at 10:56
  • Please see the edited question. This is my final case. Commented Mar 1, 2019 at 11:04

4 Answers 4

2

In your code change method .put to .post, and not required to SVProgressHUD.dismiss() in else, because you already dismiss before if else part

Also, you need to convert your JSON string(temp variable) to array and then pass with the parameter.

let parameters: Parameters = [
            "answers": temp,
            "challenge_date": "2019-03-01"
        ]

    Alamofire.request("...url", method: .post, parameters: parameters, encoding:  JSONEncoding.default , headers: headers)
        .responseJSON { response in

            if let status = response.response?.statusCode {
            let classFinal : JSON = JSON(response.result.value!)
                SVProgressHUD.dismiss()
                if status > 199 && status < 300 {                    
                     self.dismiss(animated: true)
                }
            }
    }
Sign up to request clarification or add additional context in comments.

3 Comments

yes. still getting error "JSON parse error - No JSON object could be decoded"
temp is your JSON string right?, So you need to convert JSON to the dictionary and then pass with the parameter
first, check your request and parameter with the postman, is it working fine?
0

I hope your Parameters class follows Codable protocol.

As far as I see, you are getting an error parsing that object to JSON. Hence that is the source of your error.

Could you also add code for your Parameters class / struct

Comments

0

First, convert your Temp

Array into String

than pass in that in parameters of Alamofire.

extension NSArray {
    
    func toJSonString(data : NSArray) -> String {
        
        var jsonString = "";
        
        do {
            
            let jsonData = try JSONSerialization.data(withJSONObject: data, options: .prettyPrinted)
            jsonString = NSString(data: jsonData, encoding: String.Encoding.utf8.rawValue)! as String
            
        } catch {
            print(error.localizedDescription)
        }
        
        return jsonString;
    }
    
}

2 Comments

temp is an array of json not a dictionary
Now pass your Array and get String.
0

This is for Swift 5 . Please make sure encoding must be encoding: JSONEncoding.default . temp can be simple string Array or dictionary array. This work for me .

let url = ""
    print(url)
let temp: [String] = ["",""]
  let parameters: Parameters = [
"answers": temp,
"challenge_date": "2019-03-01"]
    
    let headers: HTTPHeaders = [
        "Accept": "application/json",
        "Content-Type": "application/json"
    ]
    print(params)
    AF.request(url, method: .post, parameters: params, encoding: JSONEncoding.default, headers: headers)
        .responseJSON(completionHandler: { response in
            switch response.result {
            case .success:
            print("Success")
           case .failure(let error):
                print(error)  }
        })

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.