将json数组传递给另一个视图控制器,并使用segue将其显示在不同的标签中

时间:2018-04-05 07:18:39

标签: arrays json swift

我想将json数组发送到另一个视图控制器并在另一个视图控制器的不同标签中显示它?

var sendData = [String: AnyObject]()
sendData = datas
print("Send Data : \(sendData)")
DispatchQueue.main.async {
   self.performSegue(withIdentifier: "checkLoginViewController", sender: sendData)
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if let destinationVC = segue.destination as? signUpViewController {
            if let sendmyArray = sender as? [String]{
                destinationVC.myarray = sendmyArray
            }
}

signUpViewController.swift:

var myarray = [String]()
var myemail = ""
var myname = ""

override func viewDidLoad() {
    super.viewDidLoad()
    MynameLabel.text = myname
    nameTextfield.text = myemail
    myarray = [myemail,myname]
    print(myarray)        
    print(myemail)
    print(myname)
}

我能够获取数组,但我无法将数组发送到另一个视图控制器,我必须在不同的标签中显示它

1 个答案:

答案 0 :(得分:1)

你正在混合数组和字典

  • sendData是字典([String: AnyObject]
  • myarray是数组([String]

当然,可选的向下转发sender as? [String]失败,因为发件人是字典。

由于源是带有String键的字典,值将代码更改为

var sendData = [String: String]()

...

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
   if let destinationVC = segue.destination as? signUpViewController,
      let sendmyDictionary = sender as? [String: String] { 
         destinationVC.myDictionary = sendmyDictionary
   }
}

在第二个控制器中

var myDictionary = [String: String]()

override func viewDidLoad() {
    super.viewDidLoad()

    MynameLabel.text = myDictionary["name"]
    nameTextfield.text = myDictionary["email"]
}

注意:Swift 3+中未指定的值类型字典是[String:Any],根据命名约定,变量名称应该以小写字母开头。