Enabling outgoing network connections in Swift Playgrounds app

I am trying to develop an App in Swift Playgrounds that will use the SwiftMQTT package. SwiftMQTT needs to open an outgoing network connection to connect the app to an MQTT server. To integrate the package, I wrote a basic manager class as an observable object.

When I try to make a connection with this manager, Swift Playgrounds appears to block the connection. Searching around, I found that this was likely due to sandboxing but couldn't figure out how to fix it in Swift Playgrounds. To test this idea, I moved my manager class over to XTools and created a test app to make the connection. Initially, I got the same error. However, XTools let me make the needed sandbox setting on the Signing & Capabilities page of the app. Click/checkmarking "Outgoing Connections (Client)" under Network solved my problem there.

I would still like to do this in Playgrounds but can't for the life of me figure out how to open up the sandbox. Can anybody point me there (or wave me off if this is currently impossible).

  • In the playground console you should run PlaygroundPage.current.needsIndefiniteExecution = true after you import PlaygroundSupport to keep the program from terminating

Add a Comment

Replies

Playground should allow outgoing network connections in all cases. To test this, run a simple URLSession request like the one below:

print("will start task")
let url = URL(string: "https://example.com")!
let request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 60.0)
URLSession.shared.dataTask(with: request) { (data, response, error) in
    if let error = error as NSError? {
        print("task did fail, error \(error.domain) / \(error.code)")
        return
    }
    let response = response as! HTTPURLResponse
    let data = data!
    print("task finished with status \(response.statusCode), bytes \(data.count)")
}.resume()
print("did start task")

Does that work when you run it in your playground?

Share and Enjoy

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

  • He could be running in a “Playground” not an “App” which means he has to set PlaygroundPage.current.needsIndefiniteExecution = true. This gets everyone starting out.

Add a Comment