我正在 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.
}
}
Run Code Online (Sandbox Code Playgroud)
我有这个数组:
let arr = ["aaa", "wassd", "wesdsd"]
Run Code Online (Sandbox Code Playgroud)
现在我需要将此数组作为参数发送,如下所示:
let postParameters = "name="+teamName!+"&member="+memberCount!;
Run Code Online (Sandbox Code Playgroud)
我已经这样做了:
let postParameters = "name="+teamName!+"&member="+memberCount!+"&arr="+arr;
Run Code Online (Sandbox Code Playgroud)
但收到此错误:
表达式太长,无法在合理的时间内解决。考虑将表达式分解为不同的子表达式。
任何帮助,将不胜感激。
对您想要实现的确切目标有点困惑,但似乎您正在尝试在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
Run Code Online (Sandbox Code Playgroud)
当然,这是一种肮脏的解决方案,并且假设我对您尝试错误发送数组的看法是正确的。如果可能的话,我会将请求作为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()
}
Run Code Online (Sandbox Code Playgroud)
希望这能让你朝着正确的方向前进。祝你好运!