Reputation: 2682
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
?
Upvotes: 0
Views: 236
Reputation: 954
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()
}
Upvotes: 2