swift: методы AWSCognitoIdentityInteractiveAuthenticationDelegate не вызываются в контроллере представления входа в систему - PullRequest
0 голосов
/ 17 февраля 2019

Я пытаюсь войти в систему с помощью пула пользователей AWSCognito, но методы AWSCognitoIdentityInteractiveAuthenticationDelegate не вызываются.Вот мой код, где я делаю неправильно?

import UIKit
import AWSCognito
import AWSCognitoIdentityProvider

class LoginViewController: UIViewController,     AWSCognitoIdentityInteractiveAuthenticationDelegate {

@IBOutlet weak var cancelButton: UIButton!
@IBOutlet weak var emailTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
var passwordAuthenticationCompletion: AWSTaskCompletionSource<AWSCognitoIdentityPasswordAuthenticationDetails>?
let pool = AWSCognitoIdentityUserPool(forKey: "UserPool")
var user: AWSCognitoIdentityUser?

override func viewDidLoad() {
    super.viewDidLoad()

    loginButton.layer.cornerRadius = 10
    loginButton.layer.borderWidth = 1

    pool.delegate = self
}

@IBAction func loginTap(_ sender: Any) {
    if let email = emailTextField.text, let password = passwordTextField.text {
        if email.isValidEmail() {
            let authDetails = AWSCognitoIdentityPasswordAuthenticationDetails.init(username: email, password: password)
            self.passwordAuthenticationCompletion?.set(result: authDetails)
            self.user?.getSession()
        } else {
            let alert = UIAlertController(title: "Alert", message: "Invalid Email or password", preferredStyle: UIAlertController.Style.alert)
            alert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil))
            self.present(alert, animated: true, completion: nil)
        }
    }
}

@IBAction func cancelButtonTap(_ sender: Any) {
    dismiss(animated: true, completion: nil)
    DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
        NotificationCenter.default.post(name: NSNotification.Name("goToPaymentPageVC"), object: nil)
    }
}

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    emailTextField.resignFirstResponder()
    passwordTextField.resignFirstResponder()
}


//:- MARK: AWSCognitoIdentityInteractiveAuthenticationDelegate methods
func getDetails(_ authenticationInput: AWSCognitoIdentityPasswordAuthenticationInput, passwordAuthenticationCompletionSource: AWSTaskCompletionSource<AWSCognitoIdentityPasswordAuthenticationDetails>) {
    self.passwordAuthenticationCompletion = passwordAuthenticationCompletionSource
    DispatchQueue.main.async {
        if (self.emailTextField.text == nil) {
            self.emailTextField.text = authenticationInput.lastKnownUsername
        }
    }
}

func didCompleteStepWithError(_ error: Error?) {
    DispatchQueue.main.async {
        if let error = error as NSError? {
            let alertController = UIAlertController(title: "Error",
                                                    message: error.userInfo["message"] as? String,
                                                    preferredStyle: .alert)
            let retryAction = UIAlertAction(title: "Retry", style: .default, handler: nil)
            alertController.addAction(retryAction)

            self.present(alertController, animated: true, completion:  nil)
        } else {
            self.emailTextField.text = nil
            self.dismiss(animated: true, completion: nil)
            DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
                NotificationCenter.default.post(name: NSNotification.Name("goToPaymentPageVC"), object: nil)
            }
        }
    }
}
}

Ожидаемый результат: должны быть вызваны методы AWSCognitoIdentityInteractiveAuthenticationDelegate, а loginViewController должен быть отклонен.

Ответы [ 2 ]

0 голосов
/ 18 февраля 2019

Вот как это было исправлено:

  1. Соответствует классу LoginViewController до AWSCognitoIdentityPasswordAuthentication и добавил следующую функцию в том же классе

    func startPasswordAuthentication() -> AWSCognitoIdentityPasswordAuthentication { return self }

  2. Добавление pool.clearAll() перед вызовом self.user?.getSession()

0 голосов
/ 18 февраля 2019

Вам необходимо позвонить

pool.clearAll()

перед выполнением процедур входа в систему

let authDetails = AWSCognitoIdentityPasswordAuthenticationDetails.init(username: email, password: password)
        self.passwordAuthenticationCompletion?.set(result: authDetails)
        self.user?.getSession()

Если вы уже входили в систему на этом конкретном устройстве / симуляторе, AWS SDK не вызываетсоответствующие методы.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...