如何使用post方法从登录功能将JSON数据传递给另一个视图控制器?

时间:2017-06-28 05:37:33

标签: ios json swift3 oauth alamofire

我在另一个视图控制器中有空白数据,我可以在表视图控制器之间传递数据但我有一个问题是从登录方法解析数据并从JSON传递访问令牌或用户名?

 @IBOutlet weak var username_textfield: UITextField!
    @IBOutlet weak var password_textfield: UITextField!
var logindata : [Login] = []
 var myResponse  :   JSON    =   nil
func getlogin(){
        let headers = [
            "Content-Type": "application/x-www-form-urlencoded"
        ]
        let parameters = [

            "UserName": username_textfield.text! as String,
            "Password": password_textfield.text! as String,
            "grant_type": "password",
            ]


        //        let url = NSURL(string: "http://192.168.100.5:84/Token")!
        Alamofire.request("http://192.168.100.5:84/Token", method: .post, parameters: parameters, encoding:  URLEncoding.httpBody, headers: headers).responseJSON { (response:DataResponse<Any>) in

            switch(response.result) {
            case.success(let data):
                print("success",data)
                 let statusCode = (response.response?.statusCode)!
                if statusCode == 200{
                    self.view.makeToast(message: "Welcome !!")
                    self.performSegue(withIdentifier: "mainview", sender: self)

                }else{
                    self.view.makeToast(message: "Username or password invalid")
                }
                self.myResponse = JSON(data)
            let login = Login(loginJson: self.myResponse)
            DispatchQueue.main.async(execute: { () -> Void in
                self.performSegue(withIdentifier: "pass_data", sender: login)
            })


            case.failure(let error):
                print("Not Success",error)
            }

        }
    }

将数据传递到另一个视图控制器

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "pass_data" {
        if let eventsVC = segue.destination as? MenuDrawerViewController,
            let loginData = sender as? Login {
            eventsVC.login_details = loginData
        }
    }
}

我有模特课

class Login{

    var access_token = String()
    var token_type = String()
    var expire_in = String()
    var username = String()
    var masterid = String()
    var name = String()
    var access = String()
    var issued = String()
    var expries = String()

    init(loginJson:JSON){
    self.access_token = loginJson["access_token"].stringValue
        self.token_type = loginJson["token_type"].stringValue
        self.expire_in = loginJson["expires_in"].stringValue
        self.username = loginJson["userName"].stringValue
        self.masterid = loginJson["MasterID"].stringValue
        self.name = loginJson["Name"].stringValue
        self.access = loginJson["Access"].stringValue
        self.issued = loginJson[".issued"].stringValue
        self.expries = loginJson[".expires"].stringValue
    }


}

在第二个视图控制器中我有这样的调用类

class MenuDrawerViewController: UIViewController {
var login_details : Login?
 override func viewDidLoad() {
        super.viewDidLoad()



        titlename_text.text = login_details?.name
        // Do any additional setup after loading the view.
    }
}
  

我有点困惑我在哪里出错或者我做错了   怎么样才能解决?

我想通过导航控制器传递数据而不使用导航控制器数据传递所以我尝试这个函数传递它给我错误“if let detailController”条件

override  func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "dashboard" {
            let navController = segue.destination as! UINavigationController
           if let detailController = navController.topViewController as! ViewController,
            let loginData = sender as? Login {
                detailController.login_details = loginData
            }
        }
    }

1 个答案:

答案 0 :(得分:1)

For loop这里没有必要,因为您没有获得一系列登录数据,您需要的是直接使用self.myResponse来创建Login的对象。此外,您使用不同的标识符执行两次segue,并使用相应的目标控制器执行segue到特定标识符。

Alamofire.request("http://192.168.100.5:84/Token", method: .post, parameters: parameters, encoding:  URLEncoding.httpBody, headers: headers).responseJSON { (response:DataResponse<Any>) in

    switch(response.result) {
        case.success(let data):
            print("success",data)
            let statusCode = (response.response?.statusCode)!
            if statusCode == 200{
                self.view.makeToast(message: "Welcome !!")
            }else{
                self.view.makeToast(message: "Username or password invalid")
            }
            self.myResponse = JSON(data)
            let login = Login(loginJson: self.myResponse)
            DispatchQueue.main.async(execute: { () -> Void in
               self.performSegue(withIdentifier: "pass_data", sender: login)
            })
        case.failure(let error):
            print("Not Success",error)
    }
}

现在让你的prepareForSegue像这样

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "pass_data" {
        if let eventsVC = segue.destination as? MenuDrawerViewController,
           let loginData = sender as? Login {
              eventsVC.login_details = loginData
        }
    }
}