我正在研究需要从远程服务器获取数据的iOS应用程序。
这是从PHP脚本获取JSON数组的Swift代码:
func doSearch(_ searchWord: String)
{
// Dismiss the keyboard
// Create URL
let myUrl = URL(string: "...getAsesores.php")
// Create HTTP Request
let request = NSMutableURLRequest(url:myUrl!);
request.httpMethod = "POST";
if let x = UserDefaults.standard.object(forKey:"miCodigoAgencia") as? String
{
print (x)
}
let postString = "searchWord=\(UserDefaults.standard.object(forKey:"miCodigoAgencia"))";
print (postString)
request.httpBody = postString.data(using: String.Encoding.utf8);
// Execute HTTP Request
URLSession.shared.dataTask(with: request as URLRequest,
completionHandler: { (data, response,error) -> Void in
// Run new async task to be able to interact with UI
DispatchQueue.main.async {
// Check if error took place
if error != nil
{
// display an alert message
self.displayAlertMessage(error!.localizedDescription)
return
}
do {
// Convert data returned from server to NSDictionary
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
// Cleare old search data and reload table
self.searchResults.removeAll(keepingCapacity: false)
// If friends array is not empty, populate searchResults array
if let parseJSON = json {
if let friends = parseJSON["friends"] as? [AnyObject]
{
let primerName = ["Nombre": "Selecciona un asesor" ,"Apellidos": " ", "Id": " ", "Tel": " ", "Email": " " ]
self.searchResults.append(primerName)
for friendObj in friends
{
let fullName = ["Nombre": friendObj["nombre"] as! String, "Apellidos": friendObj["apellidos"] as! String, "Id": friendObj["id"] as! String, "Tel": friendObj["tel"] as! String, "Email": friendObj["email"] as! String]
self.searchResults.append(fullName)
}
self.pickerAsesores.reloadAllComponents()
} else if(parseJSON["message"] != nil)
{
// if no friends returned, display message returned from server side
let errorMessage = parseJSON["message"] as? String
if(errorMessage != nil)
{
// display an alert message
self.displayAlertMessage(errorMessage!)
}
}
}
} catch {
print(error);
}
} // End of dispatch_async
}) // End of data task
.resume()
} // end of doSearch() function
然后在两个文件上有PHP部分:
FILE 1 getAsesores.php:
<?php
require("../db/MySQLDAO.php");
$config = parse_ini_file('../../../SwiftPhp.ini');
$dbhost = trim($config["dbhost"]);
$dbuser = trim($config["dbuser"]);
$dbpassword = trim($config["dbpassword"]);
$dbname = trim($config["dbname"]);
$dao = new MySQLDAO($dbhost, $dbuser, $dbpassword, $dbname);
$dao->openConnection();
$searchWord = null;
if(!empty($_REQUEST["searchWord"]))
{
$searchWord = htmlentities($_REQUEST["searchWord"]);
}
$friends = $dao->buscarAsesores($searchWord);
if(!empty($friends))
{
$returnValue["friends"] = $friends;
} else {
$returnValue["message"] = "Could not find records";
}
$dao->closeConnection();
echo json_encode($returnValue);
?>
文件2:MySQLDAO.php:
public function buscarAsesores($searchWord)
{
$returnValue = array();
$sql = "select * from members LEFT JOIN tb_agencias ON members.agencia_usuario = tb_agencias.id_agencia where 1";
if(!empty($searchWord))
{
$sql .= " and ( codigo_agencia like ? )";
$sql .= " ORDER BY nombre";
}
$statement = $this->conn->prepare($sql);
if (!$statement)
throw new Exception($statement->error);
if(!empty($searchWord))
{
$searchWord = '%' ;
$statement->bind_param("s", $searchWord );
}
$statement->execute();
$result = $statement->get_result();
while ($myrow = $result->fetch_assoc())
{
$returnValue[] = $myrow;
}
return $returnValue;
}
如果我直接从浏览器调用PHP,结果不正确,查询不会按我的意愿过滤记录,iOS应用程序会显示所有记录。
如果我删除该行:
$searchWord = '%' ;
在我之前的问题中在SO Weird filter result in PHP function
处评论过 在MySQLDAO.php,然后查询按我的意愿过滤记录,但应用程序显示消息:Could not find records
欢迎任何帮助。
来自@Chris正确回答的SWIFT 3更新版本:
if let x = UserDefaults.standard.object(forKey:"miCodigoAgencia") as? String {
print (x)
var postString = "searchWord=\(x)".addingPercentEncoding(withAllowedCharacters:NSCharacterSet.urlQueryAllowed);
print (postString)
request.httpBody = postString?.data(using: String.Encoding.utf8)
request.setValue("\(request.httpBody?.count)", forHTTPHeaderField:"Content-Length")
}
答案 0 :(得分:1)
我看到了一些事情。
$searchWord
的值,始终为'%'。application/x-www-form-urlencoded
,您需要对您的值进行实际网址编码; - )对于数字1,此代码:
if(!empty($searchWord))
{
$searchWord = '%' ;
$statement->bind_param("s", $searchWord );
}
应该是这样的
if(!empty($searchWord)) {
$statement->bind_param("s", $searchWord );
}
对于iOS应用中的数字2,添加这样的代码(请注意我删除了对UserDefaults的冗余调用):
let request = NSMutableURLRequest(url:myUrl!);
request.httpMethod = "POST";
if let x = UserDefaults.standard.object(forKey:"miCodigoAgencia") as? String {
print (x)
var postString = "searchWord=\(x))".addingPercentEncoding(withAllowedCharacters:NSCharacterSet.URLQueryAllowedCharacterSet());
print (postString)
request.httpBody = postString.data(using: String.Encoding.utf8)
request.setValue("\(request.httpBody.length)", forHTTPHeaderField:"Content-Length")
}
对于3号,将" and ( codigo_agencia like ? )"
更改为" and ( codigo_agencia like %?% )"
(或仅使用后者使搜索需要与数据的开头匹配)。