可以';t将swift应用程序连接到MySQL


Can't connect swift app to MySQL

我正在使用Swift 2开发一个iOS应用程序。我希望登录信息(用户和密码)在线存储在MySQL数据库中,该数据库位于godaddy VPS服务器中。这是要注册的类:

import UIKit
class RegisterPageViewController: UIViewController {
    @IBOutlet weak var userEmailTextField: UITextField!
    @IBOutlet weak var userPasswordTextField: UITextField!
    @IBOutlet weak var repeatPasswordTextField: 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.
    }
    @IBAction func registerButtonTapped(sender: AnyObject) {
        let userEmail = userEmailTextField.text
        let userPassword = userPasswordTextField.text
        let userRepeatPassword = repeatPasswordTextField.text
        //Check for empty fields
        if(userEmail!.isEmpty || userPassword!.isEmpty || userRepeatPassword!.isEmpty) {
            //Display alert message
            displayMyAlertMessage("Todos los campos son requeridos")
            return
        }
        //Check if password match
        if(userPassword != userRepeatPassword) {
            //Display an alert message
            displayMyAlertMessage("Passwords no coinciden")
            return
        }
        //Send user data to server side
        let myURL = NSURL(string: "https://gastonberenstein.com/pruebasmysql/userRegister.php")
        let request = NSMutableURLRequest(URL: myURL!)
    request.HTTPMethod = "POST"
    let postString = "email='(userEmail)&password='(userPassword)"
    request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
        data, response, error in
        if error != nil {
            print("error='(error)")
        }
        do {
            var json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? NSDictionary
            if let parseJSON = json {
                var resultValue = parseJSON["status"] as! String!
                print("result: '(resultValue)")
                var isUserRegistered:Bool = false
                if(resultValue == "Success") {
                    isUserRegistered = true
                }
                var messageToDisplay:String = parseJSON["message"] as! String
                if(!isUserRegistered) {
                    messageToDisplay = parseJSON["message"] as! String
                }
                dispatch_async(dispatch_get_main_queue(), {
                    //Display alert message with confirmation
                    var myAlert = UIAlertController(title: "Alert", message: messageToDisplay, preferredStyle: UIAlertControllerStyle.Alert)
                    let okAction = UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default){ action in
                        self.dismissViewControllerAnimated(true, completion: nil)
                    }
                    myAlert.addAction(okAction)
                    self.presentViewController(myAlert, animated: true, completion: nil)
                })
            }
        } catch {
            print(error)
        }
    }
    task.resume()
}
func displayMyAlertMessage(userMessage:String) {
    var myAlert = UIAlertController(title:"Alert", message: userMessage, preferredStyle: UIAlertControllerStyle.Alert)
    let okAction = UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil)
    myAlert.addAction(okAction)
    self.presentViewController(myAlert, animated: true, completion: nil)
}
}

Conn.php:

<?php
  class Conn {
     public static $dbhost = "166.62.92.31";
     //public static $dbhost = "localhost"
     public static $dbuser = "gastonbe_gaston";
     public static $dbpass = "xxx";
     public static $dbname = "gastonbe_pruebasmysql";
  }
?>

MySQLDao.hp:

<?php
class MySQLDao {
    var $dbhost = null;
    var $dbuser = null;
    var $dbpass = null;
    var $conn = null;
    var $dbname = null;
    var $result = null;
    function __construct() {
        $this->dbhost = Conn::$dbhost;
        $this->dbuser = Conn::$dbuser;
        $this->dbpass = Conn::$dbpass;
        $this->dbname = Conn::$dbname;
    }
    public function openConnection() {
        $this->conn = new mysqli($this->dbhost, $this->dbuser, $this->dbpass, $this->dbname);
        if (mysqli_connect_errno())
            echo new Exception("No se pudo establecer la conexion a la base de datos");
    }
    public function getConnection() {
        return $this->conn;
    }
    public function closeConnection() {
        if ($this->conn != null)
            $this->conn->close();
    }
    public function getUserDetails($email) {
        $returnValue = array();
        $sql = "select * from users where user_email='" . $email . "'";
        $result = $this->conn->query($sql);
        if ($result != null && (mysqli_num_rows($result) >= 1)) {
            $row = $result.fetch_array(MYSQLI_ASSOC);
            if (!empty($row)) {
                $returnValue = $row;
            }
        }
        return $returnValue;
    }
    public function getUserDetailsWithPassword($email, $userPassword) {
        $returnValue = array();
        $sql = "select id, user_email from users where user_email='" . $email . "' and user_password='" .$userPassword . "'";
        $result = $this->conn->query($sql);
        if ($result != null && (mysqli_num_rows($result) >=1)) {
            $row = $result->fetch_array(MYSQLI_ASSOC);
            if (!empty($row)) {
                $returnValue = $row;
            }
        }
        return $returnValue;
    }
    public function registerUser($email, $password) {
        $sql = "insert into users set user_email=?, user_password=?";
        $statement = $this->conn->prepare($sql);
        if (!$statement)
            throw new Exception($statement->error);
        $statement->bind_param("ss", $email, $password);
        $returnValue = $statement->execute();
        return $returnValue;
    }
}
?>

registerUser.php:

    <?php
   require("Conn.php");
   require("MySQLDao.php");
   $email = htmlentities($_POST["email"]);
   $password = htmlentities($_POST["password"]);
   $returnValue = array();
   if(empty($email) || empty($password)) {
    $returnValue["status"] = "error";
    $returnValue["message"] = "Falta un campo requerido";
    echo json_encode($returnValue);
    return;
   }
   $dao = new MySQLDao();
   $dao->openConnection();
   $userDetails = $dao->getUserDetails($email);
   if(!empty($userDetails)) {
    $returnValue["status"] = "error";
    $returnValue["message"] = "El usuario ya existe";
    echo json_encode($returnValue);
    return;
   }
   $secure_password = md5($password);
   $result = $dao->registerUser($email,$secure_password);
   if($result) {
    $returnValue["status"] = "Success";
    $returnValue["message"] = "Usuario registrado";
    echo json_encode($returnValue);
    return;
   }
   $dao->closeConnection();
   ?>

当我在Xcode中运行/调试应用程序时,我在相应的字段中输入用户名和注册信息,并在第56行中放置断点:

let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {...

控制台抛出此错误:2015-11-19 14:02:16.932 userLoginAndRegistration[17265:6170848]NSURLSession/NSURL连接HTTP加载失败(kCFStreamErrorDomainSSL,-9813)

有什么帮助吗?非常感谢!如果我忘记添加任何信息,请告诉我。

我有两个错误:

  1. PHP文件的URL应以"http"开头,而不是以"https"开头
  2. 我没有在VPS服务器中安装MySQLi(在此处找到:致命错误:找不到Class';MySQLi';)。做了这些之后,它成功了!谢谢马特的建议,它帮助了我

您正在使用构建您的帖子主体

let userEmail = userEmailTextField.text
let userPassword = userPasswordTextField.text
let postString = "email='(userEmail)&password='(userPassword)"

但是userEmailuserPassword是可选的(因为text是可选的)。你应该检查postString,并确保它是你想要的,因为我相信你想做的:

let userEmail = userEmailTextField.text!
let userPassword = userPasswordTextField.text!

let userEmail = userEmailTextField.text ?? ""
let userPassword = userPasswordTextField.text ?? ""

坦率地说,你也应该对这些进行百分比转义(例如,如果密码中包含&或其他保留字符怎么办?)。例如,在Swift 2:中

extension String {
    /// Percent escape value to be added to a HTTP request
    ///
    /// This percent-escapes all characters besize the alphanumeric character set and "-", ".", "_", and "*".
    /// This will also replace spaces with the "+" character as outlined in the application/x-www-form-urlencoded spec:
    ///
    /// http://www.w3.org/TR/html5/forms.html#application/x-www-form-urlencoded-encoding-algorithm
    ///
    /// - returns: Return percent escaped string.
    func stringByAddingPercentEncodingForFormUrlencoded() -> String? {
        let allowedCharacters = NSCharacterSet(charactersInString: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._* ")
        return stringByAddingPercentEncodingWithAllowedCharacters(allowedCharacters)?.stringByReplacingOccurrencesOfString(" ", withString: "+")
    }
}

然后:

let userEmail = userEmailTextField.text!.stringByAddingPercentEncodingForFormUrlencoded()
let userPassword = userPasswordTextField.text!.stringByAddingPercentEncodingForFormUrlencoded()

或者,如果Swift 3:

extension String {
    /// Percent escape value to be added to a HTTP request
    ///
    /// This percent-escapes all characters besize the alphanumeric character set and "-", ".", "_", and "*".
    /// This will also replace spaces with the "+" character as outlined in the application/x-www-form-urlencoded spec:
    ///
    /// http://www.w3.org/TR/html5/forms.html#application/x-www-form-urlencoded-encoding-algorithm
    ///
    /// - returns: Return percent escaped string.
    func addingPercentEncodingForFormUrlencoded() -> String? {
        let allowedCharacters = CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._* ")
        return addingPercentEncoding(withAllowedCharacters: allowedCharacters)?.replacingOccurrences(of: " ", with: "+")
    }
}

let userEmail = userEmailTextField.text!.addingPercentEncodingForFormUrlencoded()
let userPassword = userPasswordTextField.text!.addingPercentEncodingForFormUrlencoded()