Transferring data through view controllers using Swift without using a storyboard

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

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 do not use Storyboard or IB, and most of the learning / solutions I have found use things specific to them.

How to transfer returned data without using it?

+4
source share
1 answer

var UberWebviewController , , [Any]?:

var dataFromAPI : [Any]?

, :

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

UberWebviewController :

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

dataFromAPI :

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

}

:

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

All Articles