Passing data between Contents and LiveViewController in a Playground Book
Passing data from the Contents.swift to the LiveViewController.swift could cause some difficulties, given that currently no official resources are available regarding this topic. Let’s see how to do it together.
#Download the Official Template
First of all you need to download the Official Template from the Apple Developer website: template
This initial project saves us a lot of time and it is ready to be used on xCode and launched on Simulator and iPad. We need to open the project with xCode and we will found the classic ViewController (LiveViewController.swift) and LiveView.storyboard, which we usually use on IOS, and the standard Contents.swift and LiveView.swift files that we use on Playground Book. What we will do is to put the left side of the Playground Book (Contents.swift) in communication with the right side (LiveViewController.swift + LiveView.storyboard).
#Setting up the Template
We need to add some files to improve our template and make it powerful. Very quickly now we can duplicate both LiveViewController.swift and both LiveView.storyboard. In the first one, that we will rename as LiveViewController_1_1.swift, we must to inerhit the parent LiveViewController and than write our code. In the second one, renamed as LiveView_1_1.storyboard, we need to associate our class LiveViewController_1_1.
#Setting up Contents.swift
Below you will find the lines of code to insert in the Contents.swift file, from which we want to send the data.
In the example the type of data we pass is String but the process can be executed for any type of data.
# Setting up LiveViewController_1_1.swift
After having correctly prepared the code that sends the data from the Contents.swift it is necessary to add the following code in the Receive function that you can copy&paste from LiveViewController.swift.
To make this part clearer, insert a storyboard label and link it to the LiveViewController_1_1.swift via @IBOutlet.
having done this we move on to the actual part of the code:
#Run & Test
Now we are ready to run and we can test the project. We need to prepare the Build and after we have transferred it to the iPad we can launch it.
By writing a string on the left side we will see, after clicking on Execute my code, the value entered will directly appear on the right side in our label.
If you intend to pass a different data type, you need to replace the data type “string” with another type as: boolean, integer etc …
You can download this project here