Kenpachi
Kenpachi

Reputation: 107

Receive user defaults which we stored when user logged in (swift3...)

1) After logging I retrieve values from a database( OK )

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.

        // Receive user defaults which we stored when user logged in

    let defaults = UserDefaults.standard
    let firstname = defaults.string(forKey: "usernameValue")
    let lastname = defaults.string(forKey: "nameValue")
    let connect_email = defaults.string(forKey: "emailValue")
    let event_mois = defaults.array(forKey: "event_mois")
    }

2) After viewDidLoad() I make an array to feed a display (OK)

var sections = [
    Section(genre: "🦁 Event du mois",
            movies: ["The Incredibles", "The Incredibles"],
            expanded: false),
    Section(genre: "💥 Top Event",
            movies: ["Guardians of the Galaxy", "The Flash", "The Avengers", "The Dark Knight"],
            expanded: false),
    Section(genre: "👻 Event Fribourg",
            movies: ["The Walking Dead", "Insidious", "Conjuring"],
            expanded: false)
]

3)I would now like to take event_mois table which I retrieved from my database to put it in var sections. But I can not use this array outside of viewDidLoad and I can not also put var sections in viewDidload.

Can someone help me? Thank you

Upvotes: 1

Views: 88

Answers (2)

David Pasztor
David Pasztor

Reputation: 54716

You just need to define sections to be an instance property of your class, then you can access it anywhere from your class.

class MyViewController: UIViewController {
    var sections: [Section]?

    override func viewDidLoad() {
        super.viewDidLoad()
        // Receive user defaults which we stored when user logged in

        let defaults = UserDefaults.standard
        let firstname = defaults.string(forKey: "usernameValue")
        let lastname = defaults.string(forKey: "nameValue")
        let connectEmail = defaults.string(forKey: "emailValue")
        guard let eventMois = defaults.array(forKey: "event_mois") as? [Section] else {return}

        if let sections = sections {
            sections.append(eventMois)
        } else {
            sections = eventMois
        }
    }

}

And use the Swift naming convention, which is lower-camelcase for variable names.

Upvotes: 0

ovidiur
ovidiur

Reputation: 338

You can not use that array in other methods since it will be out of scope. Solution : define the array as a property, in this way you can use it anywhere in the class, the property goes in the class outside all methods.

class YourClass {

    var sections : [Section] = []

    override func viewDidLoad() {
        super.viewDidLoad()
       // your code
    }
}

Upvotes: 1

Related Questions