简体   繁体   中英

How to insert data to TableView in another view controller Swift 4?

I have ViewControllerA and ViewControllerB . I make a network call in ViewControllerB ,when it success,I want to insert a data to the TableView in ViewControllerA ,so the data can appear as 1st item in the TableView .

Here is what I tried:

ViewControllerB

 var myItem = [Item]() //here is the array in ViewControllerA

Alamofire.request(MyURL!, method: .post, parameters: params, encoding: URLEncoding.httpBody, headers: headers).responseJSON{
            response in

            switch response.result{
            case .success(let result):

                let json = JSON(result)

                if let myJson = json.dictionary,let myItem = Item.init(dict: myJson){
                    self.myItem.insert(newPost, at: 0)
                    NotificationCenter.default.post(name: .reload, object: nil) //here I call notification center after insert to the array

                   self.dismiss(animated: true, completion: nil)
                   self.tabBarController?.selectedIndex = 0 //back to ViewControllerA
                }

            case .failure(let error):
                print("error = \(error)")
            }

        }

In ViewControllerA (which contain the tableView)

override func viewDidLoad() {
    super.viewDidLoad()

    NotificationCenter.default.addObserver(self, selector: #selector(updateTableView), name: .reload, object: nil)
   }  

@objc func updateTableView(_ notification: Notification){
        print("here get called")
        self.tableView.reloadData()
    }

I create an extension for the NotificationCenter

extension Notification.Name {
    static let reload = Notification.Name("reloadTableView")
} 

After done all this,the item that I insert to the array of ViewControllerB didnt appear in the 1st place of TableView in ViewControllerB .

I make a print in updateTableView() function which will call when received response from NotificationCenter in ViewControllerA ,it get called,but the data is not appear.

I cant use segue,cause the both ViewController are 2 of the tab in TabbarController.

So in this case,how can I insert the data from ViewControllerB to TableView of ViewControllerA ?

The problem is that you create a new array by this line

var myItem = [Item]()

But the viewControllerA use the different array. Try to send a new array in notification

NotificationCenter.default.post(name: .reload, object: self.myItem)

Then in viewControllerA set the new array.

@objc func updateTableView(_ notification: Notification){
        var newItems = notification.object as! [Item]

        arrayOfControllerA.append(contentsOf: newItems)
        self.tableView.reloadData()
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM