Taytee13
Taytee13

Reputation: 131

iOS- make Segue perform after data is added to array (Swift)

I'm attempting to perform a segue which passes an image array to a new view controller, but the segue is being performed before the images are added to the array- I believe this is because URLSession, which I'm using to convert a url to an image, takes time.

How would I have the Segue perform after the images are added to the array?

My code where the url is turned into the image:

// When selection is selected
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let overallArray = displayArray[indexPath.section]

    // Add Image 1 to imageArrayToBeSent
    if let imageUrl = overallArray.fullImage1 {
        let url = URL(string: imageUrl)
        URLSession.shared.dataTask(with: url!) { (data, response, error) in
            if error != nil {
                print(error!)
                return
            }
            DispatchQueue.main.async {
                self.imageArrayToBeSent.append(UIImage(data: data!)!)
            }

            }.resume()
    }

    // stringToBeSent = overallArray.fullImage1!
    performSegue(withIdentifier: "openNewViewController", sender: self)
}

My code where I call the Segue:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
 let info = segue.destination as! NewViewController
     info.imageArray = self.imageArrayToBeSent
    print(self.imageArrayToBeSent)
 }

Upvotes: 0

Views: 37

Answers (1)

Shehata Gamal
Shehata Gamal

Reputation: 100503

Do it inside the callback

DispatchQueue.main.async {
    self.imageArrayToBeSent.append(UIImage(data: data!)!)
    self.performSegue(withIdentifier: "openNewViewController", sender: self)
}

Upvotes: 2

Related Questions