当前位置 : 主页 > 手机开发 > 其它 >

Swift – 将数组作为POST请求参数发送给PHP

来源:互联网 收集:自由互联 发布时间:2021-06-11
我正在使用 Swift中的应用程序.我需要从这个应用程序调用 PHP webservice. 下面是webservice的代码: // ViewController.swift// SwiftPHPMySQL//// Created by Belal Khan on 12/08/16.// Copyright © 2016 Belal Khan. All
我正在使用 Swift中的应用程序.我需要从这个应用程序调用 PHP webservice.

下面是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.
}


}

我有这个数组:

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

现在我需要将此数组作为参数发送,如下所示:

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

我这样做了:

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

但得到这个错误:

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

任何帮助,将不胜感激.

有点困惑你正在努力实现的目标,但似乎你试图在form-url编码的请求中发送一个数组,而不是它的工作方式.

您可以遍历数组并单独将它们分配给request参数中的值,如下所示:

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

希望这可以让你朝着正确的方向前进.祝好运!

网友评论