#StackBounty: #ios #swift Images not going straight into array

Bounty: 50

I have a small problem with some code here. I am trying to populate a collection view with Five Names, descriptions and Images.

I am able to successfully to download all of the above into their respected arrays.

The problem is that the first time I perform the segue the image array has zero values in it. Then I go back a page and re-enter the page to find that all of the arrays have been populated successfully….

This is really annoying. Here is my code:

//arrays of names, descriptions and images
    var names:[String] = []
    var descriptions: [String] = []
    var imagesArray: [UIImage] = []

Heres where I get the images:

func downloadImages(){
        for x in 1...5{
            let url = URL(string: "https://www.imagesLocation.com/(x).png")
            let task = URLSession.shared.dataTask(with: url!){(data, response, error) in
                    let data = data,
                    let newImage = UIImage(data: data)
                        print("Could not load image from URL: ",url!)
                DispatchQueue.main.async {

Heres where I download the Names and Descriptions from:

 func loadDataFromFirebase() {
        // Fetch and convert data
        let db = Firestore.firestore()
        db.collection(self.shopName).getDocuments { (snapshot, err) in
            if let err = err {
                print("Error getting documents: (err)")
            } else {
                for document in snapshot!.documents {
                    let name = document.get("Name") as! String
                    let description = document.get("Description") as! String
                self.setupImages() //safe to do this here as the firebase data is valid

Heres where I setup the collection view with the Names, Description and Images array contents:

func setupImages(){
    do {
        if imagesArray.count < 5 || names.count < 5  || descriptions.count < 5 {
            throw MyError.FoundNil("Something hasnt loaded")
        self.pages = [
            Page(imageName: imagesArray[0], headerText: names[0], bodyText: descriptions[0]),
            Page(imageName: imagesArray[1], headerText: names[1], bodyText: descriptions[1]),
            Page(imageName: imagesArray[2], headerText: names[2], bodyText: descriptions[2]),
            Page(imageName: imagesArray[3], headerText: names[3], bodyText: descriptions[3]),
            Page(imageName: imagesArray[4], headerText: names[4], bodyText: descriptions[4]),
    catch {
        print("Unexpected error: (error).")

As you can see from the image below, every array is populating successfully apart from the images array:

enter image description here

Any help is welcome 🙂

Get this bounty!!!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.