URLSession Stream NDJSON Help?

I wish I could use web sockets, but this use case can only use HTTP. I'm trying to stream data from a swift client to a server that reads NDJSON.

I can upload the data just fine as single requests (it opens a new connection for each new JSON sent to the server), but if I want to maintain a persistent connection I can't figure out how to do it.

I've been messing around with uploadTask and outputStream but I can't seem to get it working.

Can someone provide me example code of how to stream this test object and test data:

struct User: Codable {
    var name: String
    var age: Int
}


let users: [User] = [
    User(name: "Alice", age: 30),
    User(name: "Bob", age: 25),
    User(name: "Charlie", age: 35),
    User(name: "David", age: 40),
    User(name: "Emma", age: 28),
    User(name: "Frank", age: 45),
    User(name: "Grace", age: 32),
    User(name: "Henry", age: 50),
    User(name: "Isabella", age: 27),
    User(name: "Jack", age: 36),
    User(name: "Katherine", age: 42),
    User(name: "Leo", age: 29),
    User(name: "Mia", age: 31),
]

For testing purposes, I want to send each user with a 2 second delay.

  • Maintain a single persistent server connection and stream each user to the server as the server reads each NdJson object as it comes in.

Love any help ASAP!

Thanks!!!

This is a question for the Apple Developer Forums.

I haven't tried it, but you really only have two options: a data task with an httpBodyStream on the URLRequest, or an upload task created using the uploadTask(withStreamedRequest:) and the properly implemented delegate method. If the server is going to stream responses, you'll have to implement the response delegate methods as well, as the closures are only ever called when the response is complete.

1 Like