我有一個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驗證」中聲明。我要附上圖片,以顯示您所出現的警報:
您是否知道'dataTask(with'異步工作? – vadian
當你想驗證嗎?並驗證後,你想要調用登錄? –
什麼是驗證登錄和登錄按鈕?輸入用戶名和密碼後funvtion調用?? –