如何从 IOS 模拟器访问我的服务器 MySql 以检索数据 swift
How to access my server MySql from IOS simulator to retrieve data swift
此代码可能有什么问题,我正在尝试进入已打开的 MAMP 服务器,我在服务器中有一个 php 文件,我正在其中测试连接等,这个:
<?php
header('Content-type: application/json');
if($_POST) {
$username = $_POST['username'];
$password = $_POST['password'];
echo $username
echo $password
if($username && $password) {
$db_name = 'DBTest';
$db_user = 'pedro';
$db_password = 'pedro';
$server_url = 'localhost';
$mysqli = new mysqli('localhost', $db_user, $db_password, $db_name);
/* check connection */
if (mysqli_connect_errno()) {
error_log("Connect failed: " . mysqli_connect_error());
echo '{"success":0,"error_message":"' . mysqli_connect_error() . '"}';
} else {
if ($stmt = $mysqli->prepare("SELECT username FROM users WHERE username = ? and password = ?")) {
$password = md5($password);
/* bind parameters for markers */
$stmt->bind_param("ss", $username, $password);
/* execute query */
$stmt->execute();
/* bind result variables */
$stmt->bind_result($id);
/* fetch value */
$stmt->fetch();
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
if ($id) {
error_log("User $username: password match.");
echo '{"success":1}';
} else {
error_log("User $username: password doesn't match.");
echo '{"success":0,"error_message":"Invalid Username/Password"}';
}
}
} else {
echo '{"success":0,"error_message":"Invalid Username/Password."}';
}
}else {
echo '{"success":0,"error_message":"Invalid Data."}';
}
?>
并且在 Xcode 该应用程序目前在 swift 中有 3 个视图,但重要的是:
//
// LogInViewController.swift
// ParkingApp
//
// Created by Pedro Alonso on 02/06/15.
// Copyright (c) 2015 Pedro Alonso. All rights reserved.
//
import UIKit
class LogInViewController: UIViewController {
@IBOutlet weak var loginLabel: UILabel!
@IBOutlet weak var usernameField: UITextField!
@IBOutlet weak var passwordField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
@IBAction func enterTapped(sender: UIButton) {
var username: String = usernameField.text
var password: String = passwordField.text
if ( username.isEmpty || password.isEmpty) {
var alertView: UIAlertView = UIAlertView()
alertView.title = "Failed"
alertView.message = "Error in the username or password"
alertView.delegate = self
alertView.addButtonWithTitle("Ok")
alertView.show()
} else {
var post: String = "username=\(username)&password=\(password)"
NSLog("Post data: %@", post)
println(post)
var url: NSURL = NSURL(string: "http://localhost:8888/jsonlogin2.php")!
var postData: NSData = post.dataUsingEncoding(NSASCIIStringEncoding, allowLossyConversion: false)!
var postLenght: String = String(postData.length)
var request: NSMutableURLRequest = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.HTTPBody = postData
request.setValue(postLenght, forHTTPHeaderField: "Content-Length")
request.setValue("application/x-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept")
var responseError: NSError?
var response: NSURLResponse?
var urlData: NSData? = NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error: &responseError)
if urlData != nil {
let res = response as! NSHTTPURLResponse!
println(urlData)
NSLog("Response code: %ld", res.statusCode)
if (res.statusCode >= 200 && res.statusCode < 300) {
var responseData: NSString = NSString(data: urlData!, encoding: NSUTF8StringEncoding)!
NSLog("Response: ==> %@", responseData)
var error: NSError?
let jsonData: NSDictionary = NSJSONSerialization.JSONObjectWithData(urlData!, options: NSJSONReadingOptions.MutableContainers, error: &error) as! NSDictionary
let succes: Int = jsonData.valueForKey("succes") as! Int
if succes == 1 {
NSLog("Login Success")
var prefs: NSUserDefaults = NSUserDefaults.standardUserDefaults()
prefs.setObject(username, forKey: "USERNAME")
prefs.setInteger(1, forKey: "ISLOGGEDIN")
prefs.synchronize()
self.dismissViewControllerAnimated(true, completion: nil)
} else {
var errorMsg: String?
if jsonData["error_message"] as? String != nil {
errorMsg = jsonData["error_message"] as! String?
} else {
errorMsg = "Unknown error"
}
var alertView: UIAlertView = UIAlertView()
alertView.title = "Sign in failed"
alertView.message = errorMsg
alertView.delegate = self
alertView.addButtonWithTitle("Ok")
alertView.show()
}
} else {
var alertView:UIAlertView = UIAlertView()
alertView.title = "Sign in Failed!"
alertView.message = "Connection Failed"
alertView.delegate = self
alertView.addButtonWithTitle("OK")
alertView.show()
}
} else {
var alertView:UIAlertView = UIAlertView()
alertView.title = "Sign in Failed!"
alertView.message = "Connection Failure"
if let error = responseError {
alertView.message = (error.localizedDescription)
}
alertView.delegate = self
alertView.addButtonWithTitle("OK")
alertView.show()
}
}
}
}
.php 文件在 /Applications/MAMP/htdocs 中,不清楚的是为什么给我响应代码 500,我不知道为什么会这样。有帮助吗??谢谢。
编辑:响应:
<NSHTTPURLResponse: 0x7fc42149ac60> { URL: http://localhost:8888/jsonlogin2.php } { status code: 500, headers {
Connection = close;
"Content-Length" = 0;
"Content-Type" = "text/html; charset=UTF-8";
Date = "Thu, 04 Jun 2015 12:11:35 GMT";
Server = "Apache/2.2.29 (Unix) mod_wsgi/3.4 Python/2.7.8 PHP/5.6.7 mod_ssl/2.2.29 OpenSSL/0.9.8zd DAV/2 mod_fastcgi/2.4.6 mod_perl/2.0.8 Perl/v5.20.0";
"X-Powered-By" = "PHP/5.6.7";
} }
我可以从模拟器中的safari访问localhost:8888,所以没有连接问题。
EDIT2:所以这显然是请求,因为它告诉我无效数据跳过所有并返回此:
2015-06-04 17:16:11.914 ParkingApp[3777:126598] Response: ==> {"success":0,"error_message":"Invalid Data."}
我完成请求的方式可能有什么问题?
EDIT2:我已经更改了代码并激活了 mysql 日志以查看查询,但是 $stmt->get_result() 或 fetch() 仍然没有做任何事情,而我做了不知道为什么。我并没有在整个过程中都这样做 IOS 但这里的简单浏览器是麻烦的部分。
修改部分:
$mysqli = new mysqli('localhost', $db_user, $db_password, $db_name);
/* check connection */
if (mysqli_connect_errno()) {
error_log("Connect failed: " . mysqli_connect_error());
echo '{"success":0,"error_message":"' . mysqli_connect_error() . '"}';
} else {
$query = "SELECT dataOne,password FROM users WHERE username = ? and password = ?";
if ($stmt = $mysqli->prepare($query)) {
//$password = md5($password);
/* bind parameters for markers */
$stmt->bind_param("ss", $username, $password);
/* execute query */
$stmt->execute();
//$stmt->debugDumpParams();
echo $stmt->sqlstate;
var_dump($stmt);
/* bind result variables */
//$stmt->bind_result($dataOne,$password);
$result = $stmt->get_result();
printf("test: ", $dataOne, $password);
//fetch value
while($stmt->fetch()) {
echo $dataOne;
}
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
if ($result != null) {
error_log("User $username: password match.");
echo '{"success":1, "dataOne:"'.$dataOne.'}';
} else {
error_log("User $username: password doesn't match.");
echo '{"success":0,"error_message":"Invalid Username/Password"}';
}
}
$stmt 没有在 get_result() 上重新调整任何东西,或者没有进入 while(fetch()) 我只是现在不知道。有帮助吗?
好吧,如果您的 Web 服务器抛出 HTTP 错误代码 500(内部错误),那是因为您的 PHP 脚本崩溃了。我会尝试阅读 php 日志,并尝试对 php 脚本进行一些调试。
也许您的 iOS 应用中的 posted 数据有问题,导致 php 脚本失败?
在这种情况下从 safari 访问 localhost:8888 并不能证明 php 脚本正在运行,因为它需要您 post 脚本执行的任何数据。 if($_POST) {
。只需浏览该脚本,if 语句将永远不会是 true
。
编辑:
有时一次验证一个组件会有所帮助。尝试针对您的服务器 (http://localhost:8888/jsonlogin2.php
) 构建一个 posts username
和 password
的简单 html 表单。当您看到它按预期运行时,请继续确保该应用程序正常运行。这样你就可以判断你的错误是在服务器上(php 脚本)还是在你的应用程序中。
这样检查$_POST
也很好:
if (!empty($_POST)) {}
这将检查 $_POST
是否为空。
您的应用也在使用 application/x-form-urlencoded
,我猜这应该是:application/x-www-form-urlencoded
.
但又一次。创建一个本地 html 表单,并确保您的 php 脚本正在运行,然后移至应用程序。
此代码可能有什么问题,我正在尝试进入已打开的 MAMP 服务器,我在服务器中有一个 php 文件,我正在其中测试连接等,这个:
<?php
header('Content-type: application/json');
if($_POST) {
$username = $_POST['username'];
$password = $_POST['password'];
echo $username
echo $password
if($username && $password) {
$db_name = 'DBTest';
$db_user = 'pedro';
$db_password = 'pedro';
$server_url = 'localhost';
$mysqli = new mysqli('localhost', $db_user, $db_password, $db_name);
/* check connection */
if (mysqli_connect_errno()) {
error_log("Connect failed: " . mysqli_connect_error());
echo '{"success":0,"error_message":"' . mysqli_connect_error() . '"}';
} else {
if ($stmt = $mysqli->prepare("SELECT username FROM users WHERE username = ? and password = ?")) {
$password = md5($password);
/* bind parameters for markers */
$stmt->bind_param("ss", $username, $password);
/* execute query */
$stmt->execute();
/* bind result variables */
$stmt->bind_result($id);
/* fetch value */
$stmt->fetch();
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
if ($id) {
error_log("User $username: password match.");
echo '{"success":1}';
} else {
error_log("User $username: password doesn't match.");
echo '{"success":0,"error_message":"Invalid Username/Password"}';
}
}
} else {
echo '{"success":0,"error_message":"Invalid Username/Password."}';
}
}else {
echo '{"success":0,"error_message":"Invalid Data."}';
}
?>
并且在 Xcode 该应用程序目前在 swift 中有 3 个视图,但重要的是:
//
// LogInViewController.swift
// ParkingApp
//
// Created by Pedro Alonso on 02/06/15.
// Copyright (c) 2015 Pedro Alonso. All rights reserved.
//
import UIKit
class LogInViewController: UIViewController {
@IBOutlet weak var loginLabel: UILabel!
@IBOutlet weak var usernameField: UITextField!
@IBOutlet weak var passwordField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
@IBAction func enterTapped(sender: UIButton) {
var username: String = usernameField.text
var password: String = passwordField.text
if ( username.isEmpty || password.isEmpty) {
var alertView: UIAlertView = UIAlertView()
alertView.title = "Failed"
alertView.message = "Error in the username or password"
alertView.delegate = self
alertView.addButtonWithTitle("Ok")
alertView.show()
} else {
var post: String = "username=\(username)&password=\(password)"
NSLog("Post data: %@", post)
println(post)
var url: NSURL = NSURL(string: "http://localhost:8888/jsonlogin2.php")!
var postData: NSData = post.dataUsingEncoding(NSASCIIStringEncoding, allowLossyConversion: false)!
var postLenght: String = String(postData.length)
var request: NSMutableURLRequest = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.HTTPBody = postData
request.setValue(postLenght, forHTTPHeaderField: "Content-Length")
request.setValue("application/x-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept")
var responseError: NSError?
var response: NSURLResponse?
var urlData: NSData? = NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error: &responseError)
if urlData != nil {
let res = response as! NSHTTPURLResponse!
println(urlData)
NSLog("Response code: %ld", res.statusCode)
if (res.statusCode >= 200 && res.statusCode < 300) {
var responseData: NSString = NSString(data: urlData!, encoding: NSUTF8StringEncoding)!
NSLog("Response: ==> %@", responseData)
var error: NSError?
let jsonData: NSDictionary = NSJSONSerialization.JSONObjectWithData(urlData!, options: NSJSONReadingOptions.MutableContainers, error: &error) as! NSDictionary
let succes: Int = jsonData.valueForKey("succes") as! Int
if succes == 1 {
NSLog("Login Success")
var prefs: NSUserDefaults = NSUserDefaults.standardUserDefaults()
prefs.setObject(username, forKey: "USERNAME")
prefs.setInteger(1, forKey: "ISLOGGEDIN")
prefs.synchronize()
self.dismissViewControllerAnimated(true, completion: nil)
} else {
var errorMsg: String?
if jsonData["error_message"] as? String != nil {
errorMsg = jsonData["error_message"] as! String?
} else {
errorMsg = "Unknown error"
}
var alertView: UIAlertView = UIAlertView()
alertView.title = "Sign in failed"
alertView.message = errorMsg
alertView.delegate = self
alertView.addButtonWithTitle("Ok")
alertView.show()
}
} else {
var alertView:UIAlertView = UIAlertView()
alertView.title = "Sign in Failed!"
alertView.message = "Connection Failed"
alertView.delegate = self
alertView.addButtonWithTitle("OK")
alertView.show()
}
} else {
var alertView:UIAlertView = UIAlertView()
alertView.title = "Sign in Failed!"
alertView.message = "Connection Failure"
if let error = responseError {
alertView.message = (error.localizedDescription)
}
alertView.delegate = self
alertView.addButtonWithTitle("OK")
alertView.show()
}
}
}
}
.php 文件在 /Applications/MAMP/htdocs 中,不清楚的是为什么给我响应代码 500,我不知道为什么会这样。有帮助吗??谢谢。
编辑:响应:
<NSHTTPURLResponse: 0x7fc42149ac60> { URL: http://localhost:8888/jsonlogin2.php } { status code: 500, headers {
Connection = close;
"Content-Length" = 0;
"Content-Type" = "text/html; charset=UTF-8";
Date = "Thu, 04 Jun 2015 12:11:35 GMT";
Server = "Apache/2.2.29 (Unix) mod_wsgi/3.4 Python/2.7.8 PHP/5.6.7 mod_ssl/2.2.29 OpenSSL/0.9.8zd DAV/2 mod_fastcgi/2.4.6 mod_perl/2.0.8 Perl/v5.20.0";
"X-Powered-By" = "PHP/5.6.7";
} }
我可以从模拟器中的safari访问localhost:8888,所以没有连接问题。
EDIT2:所以这显然是请求,因为它告诉我无效数据跳过所有并返回此:
2015-06-04 17:16:11.914 ParkingApp[3777:126598] Response: ==> {"success":0,"error_message":"Invalid Data."}
我完成请求的方式可能有什么问题?
EDIT2:我已经更改了代码并激活了 mysql 日志以查看查询,但是 $stmt->get_result() 或 fetch() 仍然没有做任何事情,而我做了不知道为什么。我并没有在整个过程中都这样做 IOS 但这里的简单浏览器是麻烦的部分。
修改部分:
$mysqli = new mysqli('localhost', $db_user, $db_password, $db_name);
/* check connection */
if (mysqli_connect_errno()) {
error_log("Connect failed: " . mysqli_connect_error());
echo '{"success":0,"error_message":"' . mysqli_connect_error() . '"}';
} else {
$query = "SELECT dataOne,password FROM users WHERE username = ? and password = ?";
if ($stmt = $mysqli->prepare($query)) {
//$password = md5($password);
/* bind parameters for markers */
$stmt->bind_param("ss", $username, $password);
/* execute query */
$stmt->execute();
//$stmt->debugDumpParams();
echo $stmt->sqlstate;
var_dump($stmt);
/* bind result variables */
//$stmt->bind_result($dataOne,$password);
$result = $stmt->get_result();
printf("test: ", $dataOne, $password);
//fetch value
while($stmt->fetch()) {
echo $dataOne;
}
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
if ($result != null) {
error_log("User $username: password match.");
echo '{"success":1, "dataOne:"'.$dataOne.'}';
} else {
error_log("User $username: password doesn't match.");
echo '{"success":0,"error_message":"Invalid Username/Password"}';
}
}
$stmt 没有在 get_result() 上重新调整任何东西,或者没有进入 while(fetch()) 我只是现在不知道。有帮助吗?
好吧,如果您的 Web 服务器抛出 HTTP 错误代码 500(内部错误),那是因为您的 PHP 脚本崩溃了。我会尝试阅读 php 日志,并尝试对 php 脚本进行一些调试。
也许您的 iOS 应用中的 posted 数据有问题,导致 php 脚本失败?
在这种情况下从 safari 访问 localhost:8888 并不能证明 php 脚本正在运行,因为它需要您 post 脚本执行的任何数据。 if($_POST) {
。只需浏览该脚本,if 语句将永远不会是 true
。
编辑:
有时一次验证一个组件会有所帮助。尝试针对您的服务器 (http://localhost:8888/jsonlogin2.php
) 构建一个 posts username
和 password
的简单 html 表单。当您看到它按预期运行时,请继续确保该应用程序正常运行。这样你就可以判断你的错误是在服务器上(php 脚本)还是在你的应用程序中。
这样检查$_POST
也很好:
if (!empty($_POST)) {}
这将检查 $_POST
是否为空。
您的应用也在使用 application/x-form-urlencoded
,我猜这应该是:application/x-www-form-urlencoded
.
但又一次。创建一个本地 html 表单,并确保您的 php 脚本正在运行,然后移至应用程序。