0

I'm doing a network request twice, in the view controllers connected to a tab bar. If I can do the network request directly in the tab bar controller, I can pass the data from there in just one network request.

I tried this but it is giving a lot of errors. - var pages : [page] = [] is an array of structs that I want to pass. It is working fine, I just need to figure out the passing part.

 override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        let feedVC = segue.destination as! FeedViewController
        let categoriesVC = segue.destination as! CategoriesGridViewController
        feedVC.pages = pages as! [[String:Any]]
        categoriesVC.pages = pages [[String:Any]]
    } 

Screenshot of my StoryBoard

I fetch from a database of images and their information. I make an array of structs and use that to display the data in the App. All of that is working fine. Page -

struct page {
    var urlsArray : [String]
    var caption : String
    var title : String
    var time : String
}
Aryan Vaid
  • 13
  • 2

1 Answers1

0

Without seeing what data you are actually trying to pass, I would guess you should create a Class (not struct) of type Page (or whatever you want to call it) and pass an array of [Page] through the view controllers. Here's an example of how to set it up:

class Page {

    private var _title: String
    private var _otherVariable: Int

    var title: String {
        return _title
    }

    var otherVariable: Int {
        return _otherVariable
    }

    init(title: String, otherVariable: Int) {
        self._title = title
        self._otherVariable = otherVariable
    }

}

//IN VIEW CONTROLLER 1

//when you get the data, set data for a Page
let item = Page(title: "Example", otherVariable: 12345)
let item2 = Page(title: "Example2", otherVariable: 67890)


//call this to segue
func segueToFeedViewController() {
    let dataToSendToNextViewController: [Page] = [item, item2] //add data here
    performSegue(withIdentifier: "ToFeedViewController", sender: dataToSendToNextViewController)
}

//use if let for safety
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let newVC = segue.destination as? FeedViewController {
        assert(sender as? [Page] != nil)
        newVC.pages = sender as! [Page]
    }
}
nicksarno
  • 3,850
  • 1
  • 13
  • 33
  • I want to send the data from the tab bar controller to 2 view controllers connected to the tab bar controller – Aryan Vaid May 31 '20 at 06:15
  • Sorry I guess I misunderstood your question. Does this answer your question? https://stackoverflow.com/questions/27651507/passing-data-between-tab-viewed-controllers-in-swift – nicksarno May 31 '20 at 06:23