Data transfer between scenes — iOS App

This topic is pretty important for me and you, because transfer data between scenes happens all the time when using a app, so we have to learn it well for sure.

In my example, I will use segue to send data to next scene, when it comes to return previous scene, I will use notification. Today’s challenge is to make a list, the data of lists will send to next scene, and there is a editing scene, if we changed the content of lists, the data of previous scene will be changed too.

Following are my core codes of sending data to next scene by segue

override func prepare(for segue: UIStoryboardSegue, sender: AnyObject?) {//prepareing data for segue
let destination = segue.destinationViewController as! DetailViewController //set segue's destination controller
if segue.identifier == "lover1Segue" { //to consider which segue I'm using
destination.loverId = loverA.id //send data to destination scene
destination.loverName = loverA.name
destination.loverCons = loverA.constellation
destination.loverImageName = loverA.photoName
}
}
@IBAction func lover1Act(_ sender: AnyObject) {
self.performSegue(withIdentifier: "lover1Segue", sender: nil)//perform segue
}

And following are my core codes for send back data to previous scene by notification

Starting scene:

func updateData(_ sender: AnyObject) {
let notiName = Notification.Name("updateData")//define the name of notification
NotificationCenter.default.post(name: notiName, object: nil, userInfo: ["loverId": self.loverId, "loverName":self.nameTxt.text!, "loverCons":self.consTxt.text!, "loverImageName":loverImageName])//send out the notification
navigationController?.popViewController(animated: true) //pop out the navigation controller back to previous scene
}

Destination scene:

func getUpdateNoti(noti:Notification) { 
let newLoverName = noti.userInfo!["loverName"] as! String //get information send by notification by id
let newLoverCons = noti.userInfo!["loverCons"] as! String
let newLoverImageName = noti.userInfo!["loverImageName"] as! String
self.loverName = newLoverName
self.loverCons = newLoverCons
self.loverImageName = newLoverImageName
}

These codes are not the whole project, just those important codes for this topic, if you want to see the whole project, you can see my gitHub.

https://github.com/imbearfly/lover.git