我試圖使用prepare(for segue:)
函數傳遞數據,但它在第二個VC中顯示爲零。我做錯了什麼?如何使用segues在視圖控制器之間傳輸數據
class ViewController: UIViewController {
var first : [String] = []
@IBOutlet weak var passField: UITextField!
@IBOutlet weak var userID: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func login(_ sender: Any) {
let user : String = self.userID.text!
let password : String = self.passField.text!
if user != "" && password != "" {
let postString = ["username":user, 「password」: password]
var request = URLRequest(url:URL(string:"http://mydomainhere.com/api/login")!)
request.httpMethod = "POST"
request.httpBody = try! JSONSerialization.data(withJSONObject: postString, options:.prettyPrinted)
let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in
if error != nil {
print("error=\(error)")
return
}
do {
if let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String: Any] {
let firstName = json["first_name"] as? String
let lastName = json["last_name"] as? String
self.first.append(firstName!) //putting into Array
self.performSegue(withIdentifier: "loginSegue", sender: self)
}
} catch {
print(error)
}
}
}
}
// data transfer to another controller
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "loginSegue" {
let secondController = segue.destination as? SecondVC
secondController?.name = first //passing to next VC //* here having the issue its not passing the data to next VC
print(first) // here first is printing perfectly
}
}
}
// second View Controller
class SecondVC: UIViewController {
var menu_vc : MenuViewController!
var name : [String]? // passing to this Array
override func viewDidLoad() {
super.viewDidLoad()
print(name) // here printing nil
}
}
在prepareForSegue中設置一個斷點,然後逐步查看發生了什麼。視圖控制器downcast可能失敗。 – Paulw11
@ Paulw11感謝您的回覆,但我沒有得到你。你能不能給我一些建議我實際需要做的事情。 –
我不能建議代碼。你所看到的代碼通常是正確的。瞭解如何使用內置於Xcode中的功能強大的調試器來瀏覽您的應用,並瞭解它在做什麼。 – Paulw11