Swift - send an array as a POST request parameter in PHP

I am working on an application in Swift. I need to call PHP webservice from this application.

Below is the 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 a parameter as follows:

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

I have done this:

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

but getting this error:

The expression was too long to be resolved within a reasonable time. consider splitting an expression into various subexpressions.

Any help would be appreciated.

+4
source share
1 answer

What confuses you exactly what you are trying to achieve is a bit confusing, but it seems like you are trying to send an array to a request form-url-encodedthat doesn't work.

, :

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 

, , , . , application/json, :

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()
}

, . !

+2

Source: https://habr.com/ru/post/1652555/


All Articles