从视图控制器中分离的文件中显示视图控制器

时间:2018-07-19 14:50:37

标签: ios swift segue alamofire uistoryboard

我有这个应用程序,该应用程序利用Alamofire向后端发送请求并返回响应,并根据响应执行该操作。我发现Alamofire代码对我的项目来说太混乱了,我想将代码解析为一行代码。为此,我将Alamofire代码块放在我的一个自定义框架库中一个名为Requests的类中。每次我从后端得到响应时,我都想运行一个函数(不是问题),然后将其segue / present / push到下一个视图控制器(问题)。

假设我有一个Request类,其中包含一个login()函数,该函数接受用户名和密码参数。调用此函数时,单行代码如下:Request.login(username, password),最后是Request.logout(),依此类推。可以在同一Xcode项目的ACommonLibrary框架中找到此函数。这将运行Alamofire代码以发送请求,然后获取响应,并以JSON格式显示“ authenticated:true”,并据此应用程序将把/ push /呈现/ push到Profile视图控制器。

我尝试使用布尔值执行此操作,如果我收到响应,则该变量将从false设置为true并由函数返回,因此我可以在if / else语句中使用它,但这没用。我通常用

尝试过
let storyboard:UIStoryboard = UIStoryboard(name: "login", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "Login") as! LoginViewController
self.present(vc, animated: true, completion: nil)

但是我得到实例成员“ present”不能用于“ Request”类型 然后我发现有人问How to present a view controller from a detached view controller?,但那也不起作用,因为那是因为我在一个故事板上有多个视图控制器。

我搜索了此错误,但没有找到其他类似错误。所以现在我在质疑这是否有可能实现,还是我必须以不同的方式来对待?任何建议都超过赞赏。预先感谢。

编辑:在下面添加了代码。

主要
->登录
->-> LoginViewController.swift

class LoginViewController: UIViewController {

    @IBOutlet weak var usernameTextField: CustomTextField!
    @IBOutlet weak var passwordTextField: CustomTextField!
    @IBOutlet weak var loginButton: UIButton!
    @IBOutlet weak var forgotPasswordButton: UIButton!
    @IBOutlet weak var navigationBar: UINavigationBar!

    override func viewWillAppear(_ animated: Bool) {
        UIApplication.shared.statusBarStyle = .lightContent
    }

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

    // MARK: - IBActions
    @IBAction func loginPressed(sender: AnyObject) {
        usernameTextField.trimSpaces()

        let username = usernameTextField.text!
        let password = passwordTextField.text!

        Request.login(username, password)
    }
}

ACommonLibrary
->后端
->-> Request.swift

public class Request {
    public class func login(_ username:String, _ password:String) {

    let headers: HTTPHeaders = [
        "Content-Type": "application/x-www-form-urlencoded"
    ]

    let parameters:Parameters = [
        "username": username,
        "password": password
    ]

    let endpoint = GlobalVariables.BaseURLString + "login"

    Alamofire.request(endpoint, method: .post, parameters: parameters, headers: headers)
    .responseJSON { response in
        switch response.result {
            case .success/*(let data)*/:
            if response.result.value != nil{
                let swiftyJsonVar = JSON(response.result.value!)

                let responseSuccess = swiftyJsonVar["success"]
                let responseMessage = swiftyJsonVar["error_message"]
                let responseSession = swiftyJsonVar["session_id"]
                let responseUserId = swiftyJsonVar["user_id"]

            if responseSession != JSON.null {
                GlobalVariables.Keychain["user_id"] = responseUserId.rawValue as? String
                GlobalVariables.Keychain["session_id"] =  responseSession.rawValue as? String
                try? GlobalVariables.Keychain.set(username, key: "username")

                if responseSuccess.boolValue {
                    let storyboard:UIStoryboard = UIStoryboard(name: "profile", bundle: nil)
                    let vc = storyboard.instantiateViewController(withIdentifier: "ProfileNavigation") as!     ProfileViewController
                    self.present(vc, animated: true, completion: nil)
                }else{
                    SCLAlertView().showNotice("Warning!", subTitle: responseMessage.stringValue)
                }
            }else{
                SCLAlertView().showError("Error logging in", subTitle: "There was an error while logging in     to your account. If this error persists, the server is down :D ")
            }
        }
        case .failure/*(let err)*/:
//          NSLog("------------------DATA START-------------------")
//          NSLog("Response String: (String(describing: err))")
            SCLAlertView().showError("Error logging in", subTitle: "There was an error while logging in to     your account. If this error persists, the server is down :D ")
//          NSLog("------------------DATA END-------------------")
        }
    }
}    

1 个答案:

答案 0 :(得分:1)

首先,您应该知道在self类的login方法中尝试使用的类方法无法访问Requests。您尝试做的事情有两种可能,如下所述。

  1. Requests不是UIViewController的子类。只有UIViewController或其子类可以显示另一个视图控制器。因此,可以利用共享应用程序的keyWindowrootViewController。方法如下:

    if responseSuccess.boolValue {
        let storyboard:UIStoryboard = UIStoryboard(name: "profile", bundle: nil)
        let vc = storyboard.instantiateViewController(withIdentifier: "ProfileNavigation") as! ProfileViewController
        let rootVC = UIApplication.shared.keyWindow?.rootViewController
        rootVC?.present(vc, animated: true, completion: nil)
    } else {
        SCLAlertView().showNotice("Warning!", subTitle: responseMessage.stringValue)
    }
    
  2. 像在login方法中一样,在进行异步网络调用的方法中使用闭包。然后在封闭中执行segues和show / present视图控制器。方法如下:

    public class Request {
    public class func login(_ username:String, _ password:String, withSuccess successHandler:@escaping (Bool) -> Void, andFailure failureHandler:@escaping (String) -> Void) {
    
        let headers: HTTPHeaders = ["Content-Type": "application/x-www-form-urlencoded"]
    
        let parameters:Parameters = ["username": username, "password": password]
    
        let endpoint = GlobalVariables.BaseURLString + "login"
    
        Alamofire.request(endpoint, method: .post, parameters: parameters, headers: headers)
            .responseJSON { response in
                switch response.result {
                case .success/*(let data)*/:
                    if response.result.value != nil{
                        let swiftyJsonVar = JSON(response.result.value!)
    
                        let responseSuccess = swiftyJsonVar["success"]
                        let responseMessage = swiftyJsonVar["error_message"]
                        let responseSession = swiftyJsonVar["session_id"]
                        let responseUserId = swiftyJsonVar["user_id"]
    
                        if responseSession != JSON.null {
                            GlobalVariables.Keychain["user_id"] = responseUserId.rawValue as? String
                            GlobalVariables.Keychain["session_id"] =  responseSession.rawValue as? String
                            try? GlobalVariables.Keychain.set(username, key: "username")
    
                            if responseSuccess.boolValue {
                                successHandler(true)
                            } else {
                                failureHandler(responseMessage.stringValue)
                            }
                        } else {
                            failureHandler("There was an error while logging in to your account. If this error persists, the server is down :D")
                        }
                    }
                case .failure/*(let err)*/:
                    failureHandler("There was an error while logging in to your account. If this error persists, the server is down :D")
                }
            }
        }
    }
    

    然后在LoginViewController

    @IBAction func loginPressed(sender: AnyObject) {
        usernameTextField.trimSpaces()
    
        let username = usernameTextField.text!
        let password = passwordTextField.text!
    
        Request.login(username,
                      password,
                      withSuccess: { (success) in
                        let vc = self.storyboard?.instantiateViewController(withIdentifier: "ProfileViewController") as! ProfileViewController
                        self.present(vc, animated: true, completion: nil)
        }) { (errorMsg) in
            SCLAlertView().showError("Error logging in", subTitle: errorMsg)
        }
    }