Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing Data through View Controllers with Swift without Using Storyboard

Tags:

ios

swift

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?

like image 880
Russell Ingram Avatar asked Dec 08 '22 05:12

Russell Ingram


1 Answers

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)
like image 118
Aaron Brager Avatar answered Dec 10 '22 18:12

Aaron Brager