尝试使用swift发送带有PHP的帖子请求

时间:2017-07-07 22:12:48

标签: php swift3

我正在尝试将用户的输入(通过UISearchBar完成)发送到我的PHP文件,以搜索商店名称数据库。但是,好像我的$ _POST变量$ searchWord是空的。

我的快捷代码:

func searchBarSearchButtonClicked(_ searchBar: UISearchBar)
{
if(searchBar.text!.isEmpty)
{
    return
}
searchBar.resignFirstResponder()
doSearch(searchWord: searchBar.text!, searchbar: searchBar )

}
func doSearch(searchWord: String, searchbar: UISearchBar){

mysearchBar = searchbar

mysearchBar.resignFirstResponder()

let myURL = NSURL(string: "http://localhost:8080/searchStore.php")

var request = URLRequest(url:myURL! as URL)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")

print("name=\(searchWord)")

let postString = "name=\(searchWord)"
request.httpBody = postString.data(using: String.Encoding.utf8)
request.addValue("application/json", forHTTPHeaderField: "Accept")

let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in

    DispatchQueue.main.async() {

        if error != nil{
            self.displayAlertMessage(userMessage: (error?.localizedDescription)!)
            return
        }
        do{
            var _: Error?
            //STOPPED HERE AS OF NOW
            let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary

            self.results.removeAll(keepingCapacity: false)
            self.tableView.reloadData()

            if let parseJSON = json{
                print("json")
                if let stores = parseJSON["stores"] as? [AnyObject]{
                    print("stores")

                    for storeOjb in stores{
                        let name = (storeOjb["name"] as! String)
                        self.results.append(name)
                    }

                    self.tableView.reloadData()

                }else if(parseJSON["message"] != nil){
                    print("message")

                    let errorMessage = parseJSON["message"] as? String
                    if(errorMessage != nil){
                        self.displayAlertMessage(userMessage: errorMessage!)

                    }
                }
            }
        } catch {
            print(error)
        }
    }

}

task.resume()
}

func displayAlertMessage(userMessage: String)
{
    let myAlert = UIAlertController(title: "Alert", message: userMessage, preferredStyle: UIAlertControllerStyle.alert);
let okAction =  UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil)
myAlert.addAction(okAction);
self.present(myAlert, animated: true, completion: nil)
}

我的php文件

<?php
require("Conn.php");
require("MySQLDao.php");

$returnValue = array();



if(empty($_POST["name"])){
    $returnValue["message"]= "Missing required field";
    echo json_encode($returnValue);
    return;
}

$searchWord =htmlentities($_POST["name"]);

$dao = new MySQLDao(Conn::$dbhost, Conn::$dbuser, Conn::$dbpass, 
Conn::$dbname);
$dao->openConnection();

$storeNames = $dao->searchStore($name);
$dao->closeConnection();

$returnValue["stores"]=$storeNames;
echo json_encode($returnValue);
?>

类MySQLDao     {

var $dbhost = null;
var $dbuser = null;
var $dbpass = null;
var $conn = null;
var $dbname = null;
var $result = null;
function __construct($dbhost, $dbuser, $dbpassword, $dbname) {
    $this->dbhost = $dbhost;
    $this->dbuser = $dbuser;
    $this->dbpass = $dbpassword;
    $this->dbname = $dbname;
}


public function openConnection() {
    $this->conn = new mysqli($this->dbhost, $this->dbuser, $this->dbpass, 
$this->dbname);
    if (mysqli_connect_errno())
        throw new Exception("Could not establish connection with database");
    $this->conn->set_charset("utf8");
}

public function closeConnection() {
    if ($this->conn != null)
        $this->conn->close();
}



public function searchStore($name){
    $returnValue =  array();
    $sql  = "SELECT * FROM stores s WHERE s.name LIKE ? ";
    $statement = $this->conn->prepare($sql);
    if(!$statement)
    throw new Exception($statement->error);
    $name = '%' .$name. "%";
    $result->bind_param("s", $name);
    $result->execute();
    $result = $statement->get_result();

while($myrow = $result->fetch_object())
{
    $returnValue[] = $myrow;
}

return $returnValue;
}


}
?>

Conn.php包含MySQL连接细节。

swift代码中的PostString正确显示用户输入(我能够通过使用断点来解决)。但是,每当我搜索任何内容时,我都会收到一条警告消息,指出“缺少必填字段”表示我的$ _POST变量$ searchWord为空。有谁知道如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

仅当请求内容类型为$_POST时,才会填充PHP x-www-form-urlencoded数组。

如果您从Swift应用程序发布application/json,则需要从php输入流解析请求正文:php://input或者您可以使用STDIN常量。< / p>

但是,我觉得您实际上打算发送x-www-form-urlencoded数据,因此请适当更改您的内容类型。