Thegasman2000 Thegasman2000 - 23 days ago 5
iOS Question

Passing variables as NSDict from Viewcontroller to Viewcontroller

I have a simple registration storyboard asking the user for their name etc. I am collecting the inputted data as UITextfields and want to pass them all to the final viewcontroller where I make it all an array and fire it off to to server. The JSON but is all working fine with test data added.

The problem I am having is that we have a custom class to send and receive items between viewcontroller. We declare
var sendItem: NSDictionary!
var receiveItem: NSDictionary!
in our baseviewcontroller and then pass objects to that and thats working fine. But for some reason this is breaking...

Sending VC

let Name2Dict = ["firstName": inputFirstName, "lastName": inputLastName]
print (inputFirstName) // Prints Variable fine
print (inputLastName) // Prints Variable fine
self.sendItem = Name2Dict as NSDictionary!


and the receiving VC

let NameVars : NSDictionary = self.receiveItem
print(NameVars["firstName"]) // Nill

let firstNameReg = Name2Array["firstName"]
let lastNameReg = Name2Array["lastName"]

let service = "registration"
let parameters: [String: Any] = ["firstName": firstNameReg,
"lastName": lastNameReg,
"email": "Johnsmith@test11.com",
"password": "12345678",
"region": "EU",
"bundleId": Bundle.main.bundleIdentifier!,
"appVersion": Bundle.main.infoDictionary?["CFBundleVersion"] as! String]


I get "Use of unresolved identifier 'Name2Array'" which makes sense but I have no idea how to fix that?

Answer

I would use a struct so that you have a proper definition of the data you are passing.

struct User {
    var firstName: String
    var lastName: String
}

Now you can create an instance of this struct and pass it to your destination view controller in prepare(for segue:)

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let destVC = segue.destinationViewController as? YourDestinationViewControllerClass {
        let user = User(firstName: inputFirstName, lastName: inputLastName)
        destVC.user = user
}

In your destination view controller:

class YourDestinationViewController {
    var user: User?

    func someFunction {
        guard let user = self.user else {
            print("User is not set")
            return
        }

        let service = "registration"
        let parameters: [String: Any] = ["firstName": user.firstName,
                                        "lastName": user.lastName,
                                        "email": "Johnsmith@test11.com",
                                        "password": "12345678",
                                        "region": "EU",
                                        "bundleId":    Bundle.main.bundleIdentifier!,
                                        "appVersion": Bundle.main.infoDictionary?["CFBundleVersion"] as! String] 
    ...
    }

}