Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift - Send an array as POST request parameter to PHP

Tags:

arrays

php

swift

I'm working on an app in Swift. I need to call PHP webservice from this app.

Below code for webservice:

//  ViewController.swift
//  SwiftPHPMySQL
//
//  Created by Belal Khan on 12/08/16.
//  Copyright © 2016 Belal Khan. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

//URL to our web service
let URL_SAVE_TEAM = "http://192.168.1.103/MyWebService/api/createteam.php"


//TextFields declarations
@IBOutlet weak var textFieldName: UITextField!
@IBOutlet weak var textFieldMember: UITextField!



//Button action method
@IBAction func buttonSave(sender: UIButton) {

    //created NSURL
    let requestURL = NSURL(string: URL_SAVE_TEAM)

    //creating NSMutableURLRequest
    let request = NSMutableURLRequest(URL: requestURL!)

    //setting the method to post
    request.HTTPMethod = "POST"

    //getting values from text fields
    let teamName=textFieldName.text
    let memberCount = textFieldMember.text

    //creating the post parameter by concatenating the keys and values from text field
    let postParameters = "name="+teamName!+"&member="+memberCount!;

    //adding the parameters to request body
    request.HTTPBody = postParameters.dataUsingEncoding(NSUTF8StringEncoding)


    //creating a task to send the post request
    let task = NSURLSession.sharedSession().dataTaskWithRequest(request){
        data, response, error in

        if error != nil{
            print("error is \(error)")
            return;
        }

        //parsing the response
        do {
            //converting resonse to NSDictionary
            let myJSON =  try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? NSDictionary

            //parsing the json
            if let parseJSON = myJSON {

                //creating a string
                var msg : String!

                //getting the json response
                msg = parseJSON["message"] as! String?

                //printing the response
                print(msg)

            }
        } catch {
            print(error)
        }

    }
    //executing the task
    task.resume()

}


override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}


}

I have this array:

let arr = ["aaa", "wassd", "wesdsd"]

Now I need to send this array as parameter like this:

let postParameters = "name="+teamName!+"&member="+memberCount!;

I've done this:

let postParameters = "name="+teamName!+"&member="+memberCount!+"&arr="+arr;

but getting this error:

Expression was too long to be solved in a reasonable time. consider breaking the expression into distinct sub expressions.

Any help would be appreciated.

like image 370
Ripa Saha Avatar asked Aug 26 '16 05:08

Ripa Saha


1 Answers

A little confused about what you are trying to achieve exactly, but it seems you are trying to send an array in a form-url-encoded request which is not how it works.

You can either iterate through the array and individually assign them to values in the request parameter with something like so:

var postParameters = "name=\(teamName)&member=\(member)"
let arr = ["aaa", "wassd", "wesdsd"]
var index = 0

for param in arr{
    postParameters += "&arr\(index)=\(item)"
    index++
}
print(postParameters) //Results all array items as parameters seperately 

Ofcourse, this is a kind of dirty solution and is assuming I'm correct about you trying to send an array incorrectly. If possible, I would send the request as an application/json request, as this would make things much easier and less dirty:

func sendRequest() {

    let sessionConfig = NSURLSessionConfiguration.defaultSessionConfiguration()

    /* Create session, and optionally set a NSURLSessionDelegate. */
    let session = NSURLSession(configuration: sessionConfig, delegate: nil, delegateQueue: nil)


    guard var URL = NSURL(string: "http://192.168.1.103/MyWebService/api/createteam.php") else {return}
    let request = NSMutableURLRequest(URL: URL)
    request.HTTPMethod = "POST"

    // Headers

    request.addValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")

    // JSON Body

    let bodyObject = [
        "name": "\(teamName)",
        "member": "\(member)",
        "arr": [
            "aaa",
            "wassd",
            "wesdsd"
        ]
    ]
    request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(bodyObject, options: [])

    /* Start a new Task */
    let task = session.dataTaskWithRequest(request, completionHandler: { (data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in
        if (error == nil) {
            // Success
            let statusCode = (response as! NSHTTPURLResponse).statusCode
            print("URL Session Task Succeeded: HTTP \(statusCode)")
        }
        else {
            // Failure
            print("URL Session Task Failed: %@", error!.localizedDescription);
        }
    })
    task.resume()
    session.finishTasksAndInvalidate()
}

Hopefully this can get you in the right direction. Good luck!

like image 72
Geoherna Avatar answered Sep 23 '22 06:09

Geoherna