我应该在Swift代码中添加些什么,以将变量传递到以下PHP脚本中?
我的PHP脚本正在等待customerName
中的值$ID = $_POST['customerName'];
如何在Swift代码中对值进行硬编码以发送值?
快捷代码:
import Foundation
protocol FeedDetailProtocol: class {
func itemsDownloaded(items: NSArray)
}
class FeedDetail: NSObject, URLSessionDataDelegate {
weak var delegate: FeedDetailProtocol!
func downloadItems() {
let url = URL(string: "https://www.example.com/test/test1.php")!
let defaultSession = Foundation.URLSession(configuration: URLSessionConfiguration.default)
var request = URLRequest(url: url)
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"**strong text**
let parameters: [String: Any] = ["customerName": "John"]
request.httpBody = parameters.percentEscaped().data(using: .utf8)
let task = defaultSession.dataTask(with: url) { (data, response, error) in
if error != nil {
print("Error")
}else {
print("details downloaded")
self.parseJSON(data!)
}
}
task.resume()
}
func parseJSON(_ data:Data) {
var jsonResult = NSArray()
do{
jsonResult = try JSONSerialization.jsonObject(with: data, options:JSONSerialization.ReadingOptions.allowFragments) as! NSArray
} catch let error as NSError {
print(error)
}
var jsonElement = NSDictionary()
let stocks = NSMutableArray()
for i in 0 ..< jsonResult.count
{
jsonElement = jsonResult[i] as! NSDictionary
let stock = DetailModel()
//the following insures none of the JsonElement values are nil through optional binding
if let rma = jsonElement["rma"] as? String,
let customer = jsonElement["customer"] as? String,
let manufacturer = jsonElement["manufacturer"] as? String,
let model = jsonElement["model"] as? String
{
stock.rma = rma
stock.manufacturer = manufacturer
stock.model = model
stock.customer = customer
}
stocks.add(stock)
}
DispatchQueue.main.async(execute: { () -> Void in
self.delegate.itemsDownloaded(items: stocks)
})
}
}
PHP脚本:
$con=mysqli_connect("localhost","username","password","dbName");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// This SQL statement selects ALL from the table 'Equipment'
$ID = $_POST['customerName'];
$sql = "SELECT customer, rma, manufacturer, model, status FROM Equipment
WHERE customer = '$ID' ";
// Check if there are results
if ($result = mysqli_query($con, $sql))
{
// Create temporary connection
$resultArray = array();
$tempArray = array();
// Look through each row
while($row = $result->fetch_object())
{
// Add each row into our results array
$tempArray = $row;
array_push($resultArray, $tempArray);
}
// Finally, encode the array to JSON and output the results
echo json_encode($resultArray);
}
mysqli_close($con);
答案 0 :(得分:0)
您的PHP代码采用POST值($ ID = $ _POST ['customerName']),因此您需要创建POST请求。
类似这样的东西:
let url = URL(string: "https://www.example.com/test1/test1.php")!
var request = URLRequest(url: url)
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
let parameters: [String: Any] = ["customerName": "John"]`