PlaygroundBluetooth with SwiftUI

I'm trying to use Bluetooth in a SwiftUI on Playgrounds. I have a running sample using UIKit, but with SwiftUI, I ran into an interesting problem.

I startet with the empty App-Sample and defined the ContentView like this:

import SwiftUI
struct ContentView: View {
    var body: some View {
        VStack {
            Text("Hello, world!")
            Button {
                print("hello")
            } label: {
                Text("press me")
            }.buttonStyle(.bordered)
        }
    }
}

The MyApp-code looks like this

import SwiftUI
import PlaygroundSupport
import PlaygroundBluetooth

@main
struct MyApp: App {
    //private var centralManager: PlaygroundBluetoothCentralManager?

    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

With this implementation, I can click on the Button and it prints the message. But if I uncomment the private var centralManager, the App does not run anymore.

Any ideas? Thanks in advance

Rainer

SwiftUI forces you to separate your view and controller code. You can’t add stateful properties to your views because views are structs that are created and destroyed at a ferocious rate. Rather, you must manage your state outside of your view structures. In some cases that’s as simple as adding the @StateObject property wrapper. However, my advice is that you watch the following WWDC sessions, which cover this issue in some depth:

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

Thanks for the quick reply. I ran through the tutorials you mentioned and I understand, I need to extract that from the view - so I did.

In Swift Playgrounds, I added another file containing a single class with just the a declaration:

import PlaygroundSupport
import PlaygroundBluetooth

class ConnectionHandler {
    //var centralManager: PlaygroundBluetoothCentralManager?
}

There is no link between a UI-Element and that class - just an additional Code-Snippet.

And that reproduces the problem - when I uncomment the declaration, playgrounds won't compile/start the app. Unfortunately, there are no error messages/warnings/whatever.

Is that maybe a principle problem with Apps in Playground (not in Xcode)

Could this be the same problem as described here?

Thank you for that hint - maybe that is the problem "under the surface".

Since Playgrounds does not provide any error message but simply refuses to "preview/run" it might well be that problem.

I tried to reproduce in a normal Playground on a Page and there I can easily combine UIKit, SwiftUI and PlaygroundBluetooth. So I guess that has something to do with the AppPlayground Environment.

PlaygroundBluetooth with SwiftUI
 
 
Q