gpt4 book ai didi

php - Swift - 将数组作为 POST 请求参数发送到 PHP

转载 作者:搜寻专家 更新时间:2023-10-31 19:29:26 24 4
gpt4 key购买 nike

我正在使用 Swift 开发一个应用程序。我需要从此应用程序调用 PHP 网络服务。

网络服务代码如下:

//  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-encoded 请求中发送一个数组,这不是它的工作原理。

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

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

希望这能让您朝着正确的方向前进。祝你好运!

关于php - Swift - 将数组作为 POST 请求参数发送到 PHP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39158840/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com