swift:如何将JSON传递给secondViewController

时间:2016-03-14 05:45:49

标签: json swift2

我想将JSON数据传递给MainMenuPageViewController。

MainMenuPageViewController UILabel(UsernameLabel)

谢谢

图片1: enter image description here

let jsonUserId: String = json["return"] as! String
if (jsonUserId != "0") {
    print("username and password correct")
    dispatch_async(dispatch_get_main_queue(), {
    let storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
    let vc = storyboard.instantiateViewControllerWithIdentifier("MainMenuPageViewController")
    self.showViewController(vc, sender: self)
    //pass the jsonUserId to MainMenuPageViewController
    //MainMenuPageViewController has UILabel(UserIdLabel)
    })
}

enter image description here

如果输入错误的用户名和密码,系统将运行到第57行,但当我输入长字符串(a,A,@等)时,警报将会出错。但是,如果我输入镜头字符串(shing,herry,123等)应用程序可以显示警报消息。 另外,如果输入空格键和(!@#$%^& *()_ +)。它会出错。 你能帮我解决这个错误吗?谢谢。

2 个答案:

答案 0 :(得分:1)

只需在MainMenuPageViewController中声明变量,如

class MainMenuPageViewController: UIViewController {

var UserIdLabel = String()

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}
}

和传递数据

  let jsonUserId: String = json["return"] as! String
 if (jsonUserId != "0") {
    print("username and password correct")
    dispatch_async(dispatch_get_main_queue(), {
        let storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
        if let vc = storyboard.instantiateViewControllerWithIdentifier("MainMenuPageViewController") as? MainMenuPageViewController {
           vc.UserIdLabel = jsonUserId
           self.showViewController(vc, sender: self)
        } 
     })
} 

答案 1 :(得分:0)

您应该在MainMenuPageViewController中创建一个属性来存储用户ID,然后在viewDidLoad中将UsernameLabel文本设置为存储的属性。

var userID:String! //在MainMenuPageViewController中定义它

然后在创建vc后,将userID属性设置为jsonUserID

if let vc = storyboard.instantiateViewControllerWithIdentifier("MainMenuPageViewController") as? MainMenuPageViewController { vc.userID = jsonUserId self.showViewController(vc, sender: self) } else { printf("The VC is not of the right type") }

override func viewDidLoad() { super.viewDidLoad() UsernameLabel.text = userID }