我正在尝试使用perfrom segue在两个不同的视图控制器中传递JSON数据,并且很容易将数据传递给单个视图控制器,或者它是否可能?
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)!
// self.myResponse = JSON(data)
// let login = Login(loginJson: self.myResponse)
if statusCode == 200{
self.view.makeToast(message: "Welcome !!")
self.myResponse = JSON(data)
let login = Login(loginJson: self.myResponse)
DispatchQueue.main.async(execute: { () -> Void in
self.performSegue(withIdentifier: "dashboard", sender: login)
self.performSegue(withIdentifier: "rear_view", sender: login)
})
//
}else{
self.view.makeToast(message: "Username or password invalid")
}
case.failure(let error):
print("Not Success",error)
self.view.makeToast(message: "Server Error!!")
}
}
}
和我准备传递我的JSON数据的地方?
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
}
}
if segue.identifier == "rear_view" {
let navController = segue.destination as! UINavigationController
if let dc = navController.topViewController as? MenuDrawerViewController,
let loginData = sender as? Login {
dc.login_details = loginData
}
}
}
当用户登录JSON数据传递给viewController但没有传递给MenuViewController,尝试在两个视图控制器中传递数据时,如何解决这个问题?还是需要一些建议?
答案 0 :(得分:1)
由于您只能转到单个控制器,因此无法直接将数据传递到ViewController
中的多个prepare(for segue)
。
但是,您有几种方法可以在多个视图控制器之间传递数据。
UserDefaults
的初始视图控制器中,然后从其他两个视图控制器访问UserDefaults
。如果数据更复杂,您可能必须使用数据库框架(例如Realm或CoreData)。编辑:使用静态属性的示例:
class FirstVC: UIViewController { //this is your initial view controller
...
let login = Login(loginJson: self.myResponse)
ThirdVC.login = loginData
DispatchQueue.main.async(execute: { () -> Void in
self.performSegue(withIdentifier: "dashboard", sender: login)
})
...
}
class SecondVC: UIViewController { // you segue here from FirstVC
}
class ThirdVC: UIViewController { //you segue here from SecondVC
static var login: Login?
override function viewDidLoad(){
super.viewDidLoad()
print(ThirdVC.login) // you can access the data sent from your FirstVC like this anywhere in ThirdVC.
}
}