Passing Data through View Controllers with Swift without Using Storyboard

11,698

Make a var on UberWebviewController of the type you want, for example [Any]?:

var dataFromAPI : [Any]?

Then set it after creating the controller but before presenting it:

let viewController = UberWebviewController()
viewController.dataFromAPI = whateverYourDataIs
self.navigationController?.presentViewController(viewController, animated: true, completion: nil)

Then within UberWebviewController, unwrap the optional:

func doSomething {
    if let myData = dataFromAPI {
        // do something with myData
    } else {
        // no data was obtained
    }
}

Alternatively, you could make dataFromAPI non-optional and pass the data in the initializer:

class UberWebviewController : UIViewController {

    var dataFromAPI : [Any]

    init(data someData : [Any]) {
        self.dataFromAPI = someData
        super.init()
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

Then just pass it during initialization:

let viewController = UberWebviewController(data: whateverYourDataIs)
self.navigationController?.presentViewController(viewController, animated: true, completion: nil)
Share:
11,698

Related videos on Youtube

Russell Ingram
Author by

Russell Ingram

An aspiring web developer.

Updated on September 15, 2022

Comments

  • Russell Ingram
    Russell Ingram over 1 year

    I am trying to create a transition between two View Controllers (the second presented modally) that passes data parsed from an API. A button is created based on this data (it affects what the button says). This is within the closure of an API call, and I store the returned data into a variable within the class (i.e. self.data = returnedData)

    let button   = UIButton.buttonWithType(UIButtonType.System) as UIButton
    button.frame = CGRectMake(0, 100, UIScreen.mainScreen().bounds.width, 50)
    button.backgroundColor = UIColor.whiteColor()
    button.setTitle("\(buttonTitleInfo)", forState: UIControlState.Normal)
    button.addTarget(self, action: "buttonAction:", forControlEvents: UIControlEvents.TouchUpInside)
    
    self.view.addSubview(button)
    

    Then:

    func buttonAction(sender:UIButton!)
    {
        // the data is usable here but I don't know how to pass it via this button 
        let viewController:UberWebviewController = UberWebviewController()
        self.navigationController?.presentViewController(viewController, animated: true, completion: nil)
    }
    

    I am not using Storyboard or IB and most of the tutorials/solutions I have found use things specific to those.

    How can I pass the returned data without using those?

  • abdulrauf618
    abdulrauf618 over 8 years
    thanks @Aaron Brager from Hamza :) , he is my office mate