Sending values between LiveView and Contents

So I'm banging my head against the desk trying to work out how to share values between the LiveView and Contents sides of a Swift Playground...


I've got a test playgroundbook with a simple UIViewController for the LiveView. This contains a button with an action that simply increments a counter and the writes the value of the counter to the PlaygroundPage.current.keyValueStore:


@IBAction func buttonTapped(_ sender: UIButton) {

self.counter = self.counter + 1

PlaygroundPage.current.keyValueStore["counter"] = .string("\(counter)")

}


I want to have a simple loop in the Contents code which just reads the updated counter value from the keyValueStore, e.g.


while true {

if case let .string(counter)? = PlaygroundPage.current.keyValueStore["counter"] {

print(counter)

sleep(1)

}

}

PlaygroundPage.current.needsIndefiniteExecution = true


Trouble is, the Contents side of the playground never sees the counter update until I tap "Stop" after "Run My Code". What's going on? Can't the two sides communicate via the keyValueStore?

Accepted Reply

Heh, turns out that we need to run the Contents-side 'while' as a separate thread:


let queue = DispatchQueue(label: "whatever", attributes: .concurrent)


queue.async {

while true {

:

}

}


Oh well. Pays the mortgage, I suppose.

Replies

Heh, turns out that we need to run the Contents-side 'while' as a separate thread:


let queue = DispatchQueue(label: "whatever", attributes: .concurrent)


queue.async {

while true {

:

}

}


Oh well. Pays the mortgage, I suppose.