[英]Using of Alamofire and completionHandler
大家好,非常感謝您的幫助! 我是編程的新手,很抱歉,如果smth看起來很愚蠢或怪異。
我正在制作我的應用程序的登錄頁面。 我有2個字段 - 電子郵件和密碼 。 我創建了一個類User,其中包含屬性email和類 ,bool isLoggedIn和func authenticateUser ,它們執行POST請求。
我的邏輯:
用戶輸入電子郵件和密碼並按“登錄”按鈕。
這會創建一個類的對象,其中isLoggedIn的值為false
並且它還向服務器執行POST請求
如果響應確認了這樣的用戶,則isLoggedIn變為true並且正在執行segue到主頁面。
對於我使用Alamofire的請求。 如果我理解正確,我只能通過使用completionhandler來改變isLoggedIn的值。 但它對我不起作用 - isLoggedIn的值不會改變,而來自第二部分代碼的resultBool變為true 。
我確定我有一個錯誤,但已經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)
}
}
}
}
來自ViewController的代碼:
@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)
}
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.