2017-07-13 142 views
1

我有一個JSON Post身份驗證來作出登錄請求,當然我需要發送用戶&密碼參數來接收填充我的HomeViewController的響應,所以我需要首先驗證這兩個參數,如果用戶不存在,當然我會發送一個提醒並禁止訪問主頁。問題是我不知道我需要使用哪種方法進行驗證,因爲我在做驗證的方式會在驗證之前引發警報。這是我的代碼:我遇到了麻煩,我的登錄身份驗證

class LoginViewController: UIViewController, LoginProtocol { 

    @IBOutlet weak var username: UITextField! 
    @IBOutlet weak var password: UITextField! 
    @IBOutlet weak var activityIndicator: UIActivityIndicatorView! 

    var user : String = "" 
    var psw : String = "" 
    var idResponse : String = "" 
    var message : String = "" 
    override func viewDidLoad() { 
     super.viewDidLoad() 
    } 

    @IBAction func validateLogin(_ sender: Any) { 
     DoLogin(self.username.text!, self.password.text!) 
    } 

    @IBAction func login(_ sender: Any) { 

     if self.idResponse != "0" { 
      validation(message: self.message) 
     } else { 
      let vc = self.storyboard!.instantiateViewController(withIdentifier: "home") as! HomeViewController 
      self.present(vc, animated: false, completion: nil) 
      vc.getUser = self.username.text! 
      vc.getPassword = self.password.text! 
     } 
    } 

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

func DoLogin(_ user:String, _ psw:String) 
    { 
     let url = URL(string: "http://162.209.99.39:8080/MiClaroBackend/auth") 
     let session = URLSession.shared 

     let request = NSMutableURLRequest(url: url!) 
     request.httpMethod = "POST" 

     self.username.text = user 
     self.password.text = psw 

     let paramToSend = ["username":user,"password":psw] 
     request.setValue("application/json", forHTTPHeaderField: "Content-Type") 
     request.httpBody = try! JSONSerialization.data(withJSONObject: paramToSend) 

     let task = session.dataTask(with: request as URLRequest, completionHandler: { 
      (data, response, error) in 

      guard let _:Data = data else 
      { 
       return 
      } 

      let json:AnyObject? 

      do { 
       json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary 
       if let parseJSON = json{ 
        let loginModel = LoginModel() 

        let defaultServiceResponse = parseJSON["defaultServiceResponse"] as! NSDictionary 
        loginModel.message = defaultServiceResponse["message"] as! String 
        loginModel.idResponse = defaultServiceResponse["idResponse"] as! Int 

        self.idResponse = String(loginModel.idResponse) 
        self.message = loginModel.message 

        print(json!) 

       } 
      } catch { 
       let error = ErrorModel() 
       error.phrase = "PARSER_ERROR" 
       error.code = -1 
       error.desc = "Parser error in login action" 
      } 
     }) 

     task.resume() 
    } 

的validateLogin方法連接到與動作一個TextView:「EditingDidEnd」。所以我需要的是當我寫完密碼後,DoLogin函數驗證存在並讓我繼續到HomeViewController,但問題是,當我點擊按鈕「Ingresar」(Login)時,它首先顯示一個空白Alert只有第二次,我點擊按鈕,它讓我立即通過。我不知道爲什麼發送Alert,如果我之前沒有調用它,我會在「func驗證」中聲明。我要附上圖片,以顯示您所出現的警報:

The Alert

+3

您是否知道'dataTask(with'異步工作? – vadian

+0

當你想驗證嗎?並驗證後,你想要調用登錄? –

+0

什麼是驗證登錄和登錄按鈕?輸入用戶名和密碼後funvtion調用?? –

回答

1

機會是你的EditingDidEnd方法調用DoLogin這是處理在後臺,當你按下登錄按鈕。因此,當您的idResponse被初始化爲「」空字符串時,您的if條件成爲true。

如果self.idResponse!=「0」

糾正這種情況,如果要檢查其空,那麼不調用驗證消息。

要做到這一點,最好的辦法是在點擊登錄按鈕後,以及萬一你成功重定向到主頁,才能調用你的DoLogin。否則顯示警報。請注意在主線程上執行UI操作。

+0

你能幫我告訴我if條件是怎麼樣的嗎?因爲我在寫像這樣沒有任何反應: 如果self.idResponse .isEmpty ==真{ }否則,如果self.idResponse = 「0」{ 驗證(消息:self.message) }!別的讓vc = self.storyboard!.instantiateViewController(withIdentifier:「home」)as! HomeViewController self.present(vc,animated:false,completion:nil) vc.getUser = self.username.text! vc.getPassword = self.password.text! } –

+1

正如您從Vadian的答案中所瞭解到的,一旦您在完成處理程序中添加了警報代碼的顯示,您將不會面對響應空問題,因此您將看不到空的警報。在您的完成處理程序中,您可以擁有有效的響應條件以及無效的響應條件,並相應地執行您的操作。成功和錯誤條件將取決於您的驗證服務將返回的響應。 –

1

先更新代碼和用戶篩選

func DoLogin(_ user:String, _ psw:String) 
    { 
     let url = URL(string: "http://162.209.99.39:8080/MiClaroBackend/auth") 
     let session = URLSession.shared 

     let request = NSMutableURLRequest(url: url!) 
     request.httpMethod = "POST" 


     let paramToSend = ["username":user,"password":psw] 
     request.setValue("application/json", forHTTPHeaderField: "Content-Type") 
     request.httpBody = try! JSONSerialization.data(withJSONObject: paramToSend) 

     let task = session.dataTask(with: request as URLRequest, completionHandler: { 
      (data, response, error) in 

      guard let _:Data = data else 
      { 
       return 
      } 

      let json:AnyObject? 

      do { 
       json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary 
       if let parseJSON = json{ 
        let loginModel = LoginModel() 

        let defaultServiceResponse = parseJSON["defaultServiceResponse"] as! NSDictionary 
        loginModel.message = defaultServiceResponse["message"] as! String 
        loginModel.idResponse = defaultServiceResponse["idResponse"] as! Int 

        self.idResponse = String(loginModel.idResponse) 
        self.message = loginModel.message 
if self.idResponse != "0" { 
      validation(message: self.message) 
     } else { 
    let vc = self.storyboard!.instantiateViewController(withIdentifier: "home") as! HomeViewController 
      self.present(vc, animated: false, completion: nil) 
      vc.getUser = user! 
      vc.getPassword = psw! 
     } 

       } 
      } catch { 
       let error = ErrorModel() 
       error.phrase = "PARSER_ERROR" 
       error.code = -1 
       error.desc = "Parser error in login action" 
      } 
     }) 

     task.resume() 
    } 
+0

對不起,但這並不奏效,因爲首先需要驗證才能在TextView上編寫用戶和密碼,因此我無法將條件放在JSON序列化中。 –

0

如果你想在imageview的應用添加報警這段代碼

var imageView = UIImageView(frame: CGRectMake(220, 10, 40, 40)) 
imageView.image = yourImage 

alert.view.addSubview(imageView)