swift - 使用 Alamofire result 和 present() 切换 View

标签 swift

我正在尝试为我的应用制作一个身份验证(登录)屏幕。我使用 Alamofire 和 SwiftyJson。但是我尝试了想到的每一个解决方案来解决我的问题。

我得到的错误:尝试呈现其 viewcontroller 不在窗口层次结构中的 viewcontroller!

问题:当我点击屏幕上的登录按钮时,我成功地从我的服务中获取了用户名和密码。我使用“response.result.isSuccess”,所以我可以在这一步之后验证用户到下一页。这是我第一次使用 alamofire,我找不到解决方案。

它发生的地方:当我从服务( bool 值)得到结果时,我想将用户重定向到下一页。我在下面用//*********Error********* 标记了它

我试图将请求放入我的 Controller ,这破坏了我的 MVC 架构,所以我需要更好的方法来做到这一点。我已经遇到此错误 2 天了。

我的休息管理类;

class restManager {
    var requestType: String?
    var page = loginPage()
    var baseURL = "myUrl" // my service url lies down here on my code
    init(type: String){
        self.requestType = type
    }
    func builder(info: userInfo){
        if(requestType == "get"){
            makeGetRequest(path: baseURL, info: info)
        }
    }

    private func makeGetRequest(path: String, info : userInfo) {
        let params : [String: String] = ["sUser" : nm, "sPass" : ps, "sToken": "''"]
        get(parameters: params)
    }

    private func get(parameters: [String: String]){
        Alamofire.request(baseURL, method:.get ,parameters: parameters).responseJSON { response in
            print("Result: \(response.result)")
            if let json = response.result.value {
                print("JSON: \(json)")
                self.page.auth(res: true)
            }
        }
    }
}

还有我的 loginPage View Controller ;

class loginPage: UIViewController, UITextFieldDelegate {
    @IBOutlet weak var logo: UIImageView!
    @IBOutlet weak var usernameTextField: UITextField!
    @IBOutlet weak var passwordTextField: UITextField!
    private var loginInfo = userInfo()
    private var mng: restManager?
    @IBAction func loginButton(_ sender: roundButton) {
        if(usernameTextField.text != "" && passwordTextField.text != ""){
            loginInfo.setUsername(info: usernameTextField.text)
            loginInfo.setPassword(info: passwordTextField.text)
            let mng = restManager(type: "get")
            mng.builder(info: loginInfo)
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.view.endEditing(true)
    }

    func auth(res: Bool){
        if (res) {
            let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
            let nextViewController = storyBoard.instantiateViewController(withIdentifier: "homePageNavCtrl") as! homePageNavCtrl
            self.present(nextViewController, animated:true, completion:nil) // *********Error********
        } else {
            let alert = UIAlertController(title: "Error", message: "Invalid username and password.", preferredStyle: UIAlertController.Style.alert)
            alert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil))
            self.present(alert, animated: true, completion: nil)
        }
    }

我想在用户登录后显示我的导航 Controller ,但它没有发生。

最佳答案

使用闭包/回调,因此在获得响应后将调用成功和错误回调。这是该方法的示例。

class func alamofireRequest(URLString: String, parameters : Parameters, method:HTTPMethod, successCallback: @escaping (NSDictionary) -> Void, errorCallBack: @escaping (String) -> Void) -> Void {

    Alamofire.request(URLString, method: method, parameters: parameters).responseJSON { response in
        print(response)
        if let JSON = response.result.value as? [String: Any] {
            print(JSON)
            successCallback(JSON as NSDictionary)
        } else {
            errorCallBack("JSON Doesn't Exist")
        }
    }

}

然后在你的类中调用这个方法

 let params : [String: String] = ["sUser" : nm, "sPass" : ps, "sToken": "''"]
        get(parameters: params)

      restManager.alamofireRequest(URLString: url,method:.get parameters: params, successCallback: { (dict) in


                // Yahoo! You get the response do whatever you want


            }) { (error) in


              // Show error

            }

关于swift - 使用 Alamofire result 和 present() 切换 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56808061/

相关文章:

arrays - 在 CoreData 中使用单个实体时如何持久重新排序项目?

ios - queryPedometerData 返回 nil 步数,即使记录了步数

node.js - Socket.IO:Swift 客户端连接到 Node.js 服务器但服务器不会注册连接?

ios - UISearchBar 在事件时与 UITableView 内容重叠

ios - 横向需要一些 Controller

swift - 带有 2 个链接的 UITextView 属性文本,每个链接都有不同的颜色不起作用

ios - Swift 项目需要很长时间才能构建。我能做些什么?

ios - 从 UIPOpOverPresentationController 获取数据值到 UIViewController?

swift - 在单元格中使用纹理 (ASyncDisplayKit)

Swift,父类(super class)中定义的函数,当从子类对象调用时返回子类的类名