2017-06-04 47 views
0

我試圖使用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 
    } 
} 
+0

在prepareForSegue中設置一個斷點,然後逐步查看發生了什麼。視圖控制器downcast可能失敗。 – Paulw11

+0

@ Paulw11感謝您的回覆,但我沒有得到你。你能不能給我一些建議我實際需要做的事情。 –

+0

我不能建議代碼。你所看到的代碼通常是正確的。瞭解如何使用內置於Xcode中的功能強大的調試器來瀏覽您的應用,並瞭解它在做什麼。 – Paulw11

回答

0

正如@Sweeper建議,它很可能是你的目的地視圖控制器嵌入UINavigationViewController,因此你segue.destination是實際上是一個UINavigationViewController,而不是SecondVC。

你可以試試這個代碼:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) { 
    var destinationViewController = segue.destination 
    if let navigationController = destinationViewController as? UINavigationController { 
     destinationViewController = navigationController.visibleViewController ?? destinationViewController 
    } 
    if let secondController = destinationViewController as? SecondVC { 
     secondController?.name = first 
    } 
} 

當然代碼的前四行可以在適當的功能(如果UIViewController中的延伸甚至更好)進行重構。

如果解決了這個問題,您可以觀看cs193p Stanford iOS課程以獲取更多詳細信息。 特別是手錶https://www.youtube.com/watch?v=HQrXM2zUPvY&index=6&list=PLPA-ayBrweUz32NSgNZdl0_QISw-f12Ai從30:20開始。

+0

很棒。完美地工作。謝謝! –

0

一切似乎完美與下面的代碼片段

var first : [String] = [] 

@IBAction func btnTapped(_ sender: Any) { 
    let firstName = "iOS Geek" 
    self.first.append(firstName) 

    self.performSegue(withIdentifier: "MovetoSecVC", sender: self) 
} 


override func prepare(for segue: UIStoryboardSegue, sender: Any?) { 
     if segue.identifier == "MovetoSecVC"{ 

     let secVC = segue.destination as! SecondVC 
     secVC.name = first 
     print(first) // it'll print here ["iOS Geek"] 
    } 
} 

// Your Second View Controller 

class SecondVC: UIViewController { 

var menu_vc : MenuViewController! 
var name : [String]? // passing to this Array 

override func viewDidLoad() { 
    super.viewDidLoad() 

    print(name!) // it'll print here ["iOS Geek"] 
    } 
} 
相關問題