Using of Alamofire and completionHandler



大家好,非常感谢您的帮助!我是编程新手,所以很抱歉,如果smth看起来很愚蠢或奇怪。

我正在制作我的应用程序的登录页面。我有 2 个字段 -电子邮件密码。我创建了一个具有属性电子邮件和类的用户,boolisLoggedIn和 funcauthenticateUser,它执行 POST 请求。

我的逻辑:

  1. 用户输入电子邮件密码,然后按登录按钮。

  2. 这将创建一个类的对象,其isLoggedIn的值为false

  3. 并且它还对服务器执行POST请求

  4. 如果响应确认此类用户,则正在执行 isLoggedIn更改为true并登录到主页。

对于请求,我使用Alamofire。如果我理解正确,我只能通过使用完成处理程序来更改isLoggedIn的值。但它对我不起作用 -isLoggedIn的值不会改变,而代码第二部分的结果布尔变为

我确定我有一个错误,但已经 4 天我不明白在哪里了。我将非常感谢任何形式的建议和帮助。

有我的代码:

import Foundation
import Alamofire

class User {

let defaults = UserDefaults.standard
var email: String
var password: String
var isLoggedIn: Bool
init(email: String, password: String) {
self.email = email
self.password = password
self.isLoggedIn = false
}
// Perform authentication
func authenticateUser(user: User, completionHandler: @escaping (_ result: Bool) -> ()) {
makeAuthenticateUserCall(user: user, completionHandler: completionHandler)
}
// Perform POST request
func makeAuthenticateUserCall(user: User, completionHandler: @escaping (Bool) -> ()) {
let parameters = [
"email" : user.email,
"password" : user.password
]
Alamofire.request("http://apistaging.server.com/api/v1/login", method: .post, parameters: parameters, encoding:  URLEncoding.httpBody).responseJSON {response in
switch response.result {
case .success:
if let json = response.result.value as? [String: Any],
let status = json["status"] as? String,
status == "success" {
completionHandler(true)
}
case .failure:
completionHandler(false)
}
}
}
}

来自视图控制器的代码:

@IBAction func loginButtonPressed(_ sender: UIButton) {
if let email = _email.text {
if let password = _password.text {
let user = User(email: email, password: password)
user.authenticateUser(user: user) {resultBool in
user.isLoggedIn = resultBool
}
if user.isLoggedIn {
self.performSegue(withIdentifier: "MainPageViewController", sender: nil)
}
}
}
}

您在实际返回结果之前检查了结果:

if let password = _password.text {
let user = User(email: email, password: password)
user.authenticateUser(user: user) {resultBool in
user.isLoggedIn = resultBool
if resultBool {
DispatchQueue.main.async {
self.performSegue(withIdentifier: "MainPageViewController", sender: nil)
}
}
}
}

最新更新