0

How can I pass an array to my Php backend using swift. Do i have to for loop each value and append it to the request body?

Here is my code

        let url = URL(string: "url.com/page")!
        var request = URLRequest(url: url)
        request.httpMethod = "POST"


        let id = user?["id"] as! String
        let party = partyName.text!

        let body = "id=\(id)&party_name=\(party)&party_invited=\(usersInvited)" 

        //********--usersInvited-- is the array i want to pass



        request.httpBody = body.data(using: String.Encoding.utf8)

        URLSession.shared.dataTask(with: request, completionHandler: { (data:Data?, response:URLResponse?, error:Error?) in

            DispatchQueue.main.async(execute: {

                if error == nil{

                    do{
                        let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary


                        guard let parseJSON = json else{
                            print("Error while parsing")
                            return
                        }


                       print(parseJSON["status"])

                    } catch{

                        print("Caught an error: \(error)")
                    }


                } else{
                    print("Error: \(error)")
                }

            })
        }).resume()

But that code sends the array as one whole string with an output like this: ["57", "60"]

1 Answer 1

1

I'm guessing, but it looks like you want to JSON encode your array, but as a URL parameter?

(I've assumed that usersInvited is an array of strings)

You could go via JSONSerialisation?

let data = try! JSONSerialization.data(withJSONObject: usersInvited, options: [])
let string = String(data: d, encoding: .utf8)!

let body = "id=\(id)&party_name=\(party)&party_invited=\(string)"

Or if that's not quite what you want (you've got a space after the comma in your question), you could just do it by hand?

let string = "[" + usersInvited.map { "\"\($0)\"" }.joined(separator: ", ") + "]"

My vote would be to use option 1 and make your server accept what it outputs.


If you mean you want it to look like party_invited=1,2,3,4 then you could use joined to convert the array like this

let string = usersInvited.joined(separator: ",")

let body = "id=\(id)&party_name=\(party)&party_invited=\(string)"

If you mean you want this party_invited=1&party_invited=2&party_invited=3 then you can use map and joined

let string = usersInvited.map { "party_invited=\($0)" }.joined(separator: "&")

let body = "id=\(id)&party_name=\(party)&\(string)"
Sign up to request clarification or add additional context in comments.

1 Comment

I ended up using your 3rd idea where I sent party_invited separated by commas like party_invited = 1,2,3,4 and then split them up and put them in an array in Php. Works great ty

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.