2017-05-30 100 views
-1

我正在建立一個使用MySQL服務器和PHP文件上傳到FTP的密碼應用程序的簡單登錄。我一直在嘗試許多不同的方式來讓連接在模擬器上工作,但迄今爲止無濟於事。我正在使用Swift 3.0和XCode 8.3.2。我犯了一個錯誤,但我不知道在哪裏!另外,我已經在info.plist中設置允許任意負載爲YES。任何幫助表示讚賞。
來自XCode的MySQL服務器查詢

在很多教程中,我看到我看到過這個彈出窗口,我從來沒有得到過。 Pop up in tutorial I don't ever get

Simulator image #1

Simulator image #2

在我Login.swift

import UIKit 

class Login: UITableViewController { 
    @IBOutlet weak var txtUsername: UITextField! 
    @IBOutlet weak var txtPassword: UITextField! 
    @IBOutlet weak var loginView: UIButton! 
    @IBOutlet weak var btnPasswordView: UIButton! 
    var passwordString:String! 
    var usernameString:String! 

    override func viewDidLoad() { 
     super.viewDidLoad() 
     passwordViewConfig() 

    } 

    //Function PasswordView. 
    func passwordViewConfig() { 
     txtPassword.isSecureTextEntry = true 
     btnPasswordView.setImage(UIImage(named: "EyeClosedIcon"), for: UIControlState.normal) 


    } 
    //Action change image PasswordView 
    @IBAction func btnPasswordViewAction(_ sender: Any) { 
     passwordString = txtPassword.text 
     if btnPasswordView.currentImage!.isEqual(UIImage(named: "EyeClosedIcon")) { 
      btnPasswordView.setImage(UIImage(named: "EyeOpenIcon"), for: UIControlState.normal) 
      txtPassword.isSecureTextEntry = false 
      txtPassword.text = nil 
      txtPassword.text = passwordString 
     } else { 
      btnPasswordView.setImage(UIImage(named: "EyeClosedIcon"), for: UIControlState.normal) 
      txtPassword.isSecureTextEntry = true 
      txtPassword.text = passwordString 
     } 

    } 
    //Redirect select cell to textField 
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { 
     if indexPath.section == 0 && indexPath.row == 0 { 
      txtUsername.becomeFirstResponder() 
     } 

     if indexPath.section == 0 && indexPath.row == 1 { 
      txtPassword.becomeFirstResponder() 
     } 
    } 
    //Function config Return key 
    func textFieldShouldReturn(textField: UITextField) -> Bool { 
     if textField == txtUsername { 
      textField.resignFirstResponder() 
      txtPassword.becomeFirstResponder() 
     } 
     if textField == txtPassword { 
      usernameString = txtUsername.text 
      passwordString = txtPassword.text 
      if usernameString.isEmpty || passwordString.isEmpty { 
       textField.resignFirstResponder() 
       txtUsername.becomeFirstResponder() 
      } else { 
       loginAction(self) 
      } 
     } 
     return true 
     } 

    //Function config background image login button 
    func loginViewConfig() { 


    } 

    @IBAction func loginAction(_ sender: Any) { 
     usernameString = txtUsername.text 
     passwordString = txtPassword.text 
     if usernameString.isEmpty || passwordString.isEmpty { 
      let alertAction:UIAlertAction = UIAlertAction(title: "Close", style: UIAlertActionStyle.default, handler: { (alert) -> Void in 
       self.txtUsername.becomeFirstResponder() 
      }) 
      alertView(title: "Error !", message: "Please fill in all fields", alertStyle: UIAlertControllerStyle.alert, alertAction: alertAction) 
     } else { 
      queryToServerLogin() 
     } 

    } 

    func queryToServerLogin() { 
     let url:String = "here is URL to my login.php file" 
     /* 
     $username = htmlentities($_GET['username']); 
     $password = md5(htmlentities($_GET['username'])); 
     */ 
     let postString:String = "username=\(usernameString)&password=\(passwordString)" 
     print ("username=\(usernameString!)&password=\(passwordString!)") 

     self.queryToServer(urlSource: url, postString: postString) { (dataResult, errorResult) ->() in 
      if errorResult != nil { 
       let alertAction:UIAlertAction = UIAlertAction(title: "Close", style: UIAlertActionStyle.default, handler: nil) 
       self.alertView(title: "Error !", message: "Could not connect to server", alertStyle: UIAlertControllerStyle.alert, alertAction: alertAction) 
       } else { 
       self.extractDataWithNSDictionary(data: dataResult! as NSData, result: { (statusResult, messageResult, errorResult) ->() in 
        if errorResult !== nil { 
         print(errorResult as Any) 
         let alertAction:UIAlertAction = UIAlertAction(title: "Close", style: UIAlertActionStyle.default, handler: nil) 
         self.alertView(title: "Error !", message: "Could not query to server.", alertStyle: UIAlertControllerStyle.alert, alertAction: alertAction) 
        } else { 
         if statusResult == "success" { 
          let alertAction:UIAlertAction = UIAlertAction(title: "Close", style: UIAlertActionStyle.default, handler: nil) 
          self.alertView(title: "Success !", message: messageResult!, alertStyle: UIAlertControllerStyle.alert, alertAction: alertAction) 
          } else { 
           if statusResult == "success" { 
            let alertAction:UIAlertAction = UIAlertAction(title: "Close", style: UIAlertActionStyle.default, handler: nil) 
            self.alertView(title: "Error !", message: messageResult!, alertStyle: UIAlertControllerStyle.alert, alertAction: alertAction) 
          } 
         } 
       } 
      } 

     )} 
    } 
} 
} 

在我Extensions.swift

import Foundation 
import UIKit 
extension UIViewController { 
    func makeImageViewWithColor(_ color: UIColor) -> UIImage { 
     let rect: CGRect = CGRect (x: 0, y: 0, width: 1, height: 1) 
     color.setFill() 
     UIRectFill(rect) 
     let image:UIImage = UIGraphicsGetImageFromCurrentImageContext()! 
     UIGraphicsEndImageContext() 
     return image 
    } 
    //Function Alert View 
    func alertView(title:String, message:String, alertStyle:UIAlertControllerStyle, alertAction:UIAlertAction) { 
     let alert:UIAlertController = UIAlertController(title: title, message: message, preferredStyle: alertStyle) 
     alert.addAction(alertAction) 
     self.present(alert, animated: true, completion: nil) 
    } 

    //Function query to server 
    func queryToServer(urlSource:String, postString:String, result:@escaping (Data?, Error?) ->()) { 
     let url = URL(string: urlSource)! 
     var request = URLRequest (url: url, cachePolicy: .reloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 10) 
     request.httpMethod = "POST"; 
     request.addValue("application/json", forHTTPHeaderField: "Content-Type") 
     request.httpBody = postString.data(using: .utf8) 
     let session = URLSession.shared 
     session.dataTask(with: request) { (data, response, error) in 
      DispatchQueue.main.async { 
       result(data, error) 
      } 
      }.resume() 
     } 

     //Function extract data 
     func extractDataWithNSDictionary(data:NSData, result:(_ statusResult:String?, _ messageResult:String?, _ errorResult:NSError?) ->()){ 
      var json:NSDictionary! 
      var errorParse:NSError! 
      do { 
      json = try JSONSerialization.jsonObject(with: data as Data, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSDictionary 
     } catch let error as NSError { 
      errorParse = error 
      json = nil 
     } 
     if errorParse != nil { 
      result(nil, nil, errorParse) 
     } else { 
      let resultStatus:String = json["status"] as! String 
      let resultMessage:String = json["message"] as! String 
      result(resultStatus, resultMessage, nil) 
    } 
} 

} 

然後在我的FTP根我有沒有工作

[section] 
dbhost = mysql url 
dbuser = username 
dbpass = password 
dbname = database name 

另外一個mysql.php

<?php 

class mysql 
{ 
    var $dbhost = null; 
    var $dbuser = null; 
    var $dbpass = null; 
    var $dbname = null; 
    var $conn = null; 
    var $result = null; 
    function _construct() 
    { 
     $mysqlfile = parse_ini_file('MySQL.ini'); 
     $this->dbhost = $mysqlfile['dbhost']; 
     $this->dbuser = $mysqlfile['dbuser']; 
     $this->dbpass = $mysqlfile['dbpass']; 
     $this->dbname = $mysqlfile['dbname']; 

    } 
    //Function connect to sql 
    public function connection() { 
     //$this->conn = new mysqli($this->dbhost, $this->dbuser, $this->dbpass, $this->dbname); 
     $this->conn = new mysqli('mysql url', 'username', 'password', 'database name'); 
     if (mysqli_connect_error()){ 
      return false; 
     } 
     mysqli_set_charset($this->conn, 'utf8'); 
     return true; 
    } 
    //Function close sql 
    public function closeConecttion() { 
     if ($this->conn !=null) { 
      mysqli_close($this->conn); 
     } 
    } 

    //function check username does not exits 
    public function checkUsername($username) { 
     $sql = "SELECT authentication_username FROM time_employee WHERE authentication_username = '$username'"; 
     $this->result = mysqli_query($this->conn, $sql); 
     if (mysqli_num_rows($this->result) <= 0) { 
      return false; 
     } 
     return true; 
    } 

    //function check password username 
    public function checkPasswordUsername($username, $password) { 
     $sql = "SELECT authentication_username, authentication_password FROM time_employee WHERE authentication_username = '$username'"; 
     $this->result = mysqli_query($this->conn, $sql); 
     $row = mysqli_fetch_array($this->result); 
     if ($row['password'] != $password) { 
      return false; 
     } 
     return true; 
    } 

} 

而一個一個的login.php文件MySQL.ini

<?php 

include_once('mysql.php'); 
$mysql = new mysql(); 
$username = htmlentities($_REQUEST['username']); 
$password = md5(htmlentities($_REQUEST['password'])); 
$resultValue = array(); 
//Function check connect to database 
if ($mysql->connection()) { 
    //Function check username exist 
    //if !mysql->checkUsername($username) return false 
    if(!$mysql->checkUsername($username)) { 
     $resultValue['status'] = "error"; 
     $resultValue['message'] = "username does not exist"; 
     echo json_encode($resultValue); 
    } else { 
     //Function check password 
     //If !$mysql->checkPasswordUsername($username, $password) return false 
     if (!$mysql->checkPasswordUsername($username, $password)) { 
      $resultValue['status'] = "error"; 
      $resultValue['message'] = "Incorrect password"; 
      echo json_encode($resultValue); 
     } else { 
      $resultValue['status'] = "success"; 
      $resultValue['message'] = "Logged in successfully"; 
      echo json_encode($resultValue); 
     } 
    } 
} else { 
    $resultValue['status'] = "error"; 
    $resultValue['message'] = "could not connect to database"; 
    echo json_encode($resultValue); 
} 
?> 
<?php exit; ?> 
+0

你會得到什麼錯誤? –

+0

真的沒有錯誤,我聽說應該彈出模擬器彈出,所以我可以連接到服務器,但它永遠不會出現。 –

+0

你真的需要從這個問題中刪除很多無關的信息。只要說出哪一部分代碼失敗了,你的輸入是什麼以及結果如何。當你在queryToServerLogin中得到一個errorResult時,你是否檢查過它是什麼? – Spads

回答

0

I als Ø注意到你在表單的用戶名發送您的文章數據= ... &密碼= ...但在queryToServer(),你也行

request.addValue("application/json", forHTTPHeaderField: "Content-Type") 

你是說你有附加的數據是JSON時,不是。試試這個。

request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") 
+0

我試過這個,但仍然相同的錯誤{」狀態「:錯誤」 ,「message」:「用戶名不存在」} –

+0

將你正在查看的用戶名添加到你的錯誤信息中,以確保它正在通過 – Spads

+0

我該怎麼做? ö,ö –