ShingHung
ShingHung

Reputation: 337

swift: how to pass JSON to secondViewController

I want to pass the JSON data to MainMenuPageViewController.

MainMenuPageViewController UILabel(UsernameLabel)

Thank you

Picture1: 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

If I input wrong username and password, system will run to line 57 but the alert will error, when I input long String(a,A,@,etc.). However, if I input shot String(shing, herry,123,etc.) app can display the alert message. Also, if input the space bar and (!@#$%^&*()_+). it will error. Can you help me to fix this error? Thank you.

Upvotes: 0

Views: 51

Answers (2)

Bhavin Bhadani
Bhavin Bhadani

Reputation: 22374

Just declare variable in MainMenuPageViewController like

class MainMenuPageViewController: UIViewController {

var UserIdLabel = String()

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

and for pass data

  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)
        } 
     })
} 

Upvotes: 1

Pradeep K
Pradeep K

Reputation: 3661

You should create a property in the MainMenuPageViewController to store the user id and then in viewDidLoad set the UsernameLabel text to the stored property.

var userID:String! //define this in the MainMenuPageViewController

Then after you create the vc set the userID property to the 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 }

Upvotes: 0

Related Questions