简体   繁体   中英

How to use PrepareForSegue when a segue is performed programmatically

I have 2 views within my storyboard. The first view is a login screen, where the user enters the email and password, after clicking the login button a function creates a HTTP connection with the API and the API checks and authenticates the user and sends back JSON data. Now the JSON data is in VIEW 1. I have programmatically performed my segue as seen in the code below:

    dispatch_async(dispatch_get_main_queue()) {

            let storyboard = UIStoryboard(name: "Main", bundle: nil)
            let vc = storyboard.instantiateViewControllerWithIdentifier("detailView") as! UIViewController
            self.presentViewController(vc, animated: true, completion: nil)
                }

How can I pass the JSON data from VIEW 1 to VIEW 2? I tried to use prepareForSegue by that asks for the segue identifier and because I have programmatically performed my segue I don't have segue identifier. My Storyboard image is below:

在此处输入图片说明

Any help will be greatly appreciated. Thanks in advance. If you need more information to answer the question then please let me know.

instead of this you can set a function in your new class and push data to it like this:

dispatch_async(dispatch_get_main_queue()) {
            let storyboard = UIStoryboard(name: "Main", bundle: nil)
            let vc = storyboard.instantiateViewControllerWithIdentifier("detailView") as! UIViewController
            vc.setJSONObject(yourJSON)
            self.presentViewController(vc, animated: true, completion: nil)
}

In your UIViewController you can define a function called setJSONObject

func setJSONObject(json:AnyObject){
     print(json)
}

Create a segue in Interface Builder with an identifier.

Use the following code to execute the segue:

self.performSegueWithIdentifier("MySegue", sender: self);

This way prepareForSegue will be executed.

Here is an example of what that may look like in your case

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

    if (segue.identifier == "MySegue")
    {
        if let detailsViewController = segue.destinationViewController as? DetailViewController {
            detailsViewController.jsonData = YOUR_JSON_STUFF;
        }

    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM