Skip to content

A lightweight WebSocket implementation in Swift using Combine.

License

Notifications You must be signed in to change notification settings

connorprzybyla/real-time-ios

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

7 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

A lightweight, testable, and scalable Swift package for all your WebSocket needs.

This package is open-sourced and built to support devices across Apple's ecosystem including iOS, iPadOS, watchOS, tvOS, and macOS.

Setup:

First, you'll need to add this package to your Xcode project. See Apple's official docs if you don't already know how to. View them here

How to use WebSocketManager

  • Create an instance of WebSocketManager. WebSocketManager is a generic class that requires a decodable type. This type is the model you want to use for message decoding.

Example of a websocket message for real-time stock information

{
  "stocks": [
    {
      "name": "Apple Inc.",
      "sym": "AAPL",
      "price": 141.66
    },
    {
      "name": "Snap Inc.",
      "sym": "SNAP",
      "price": 14.7
    },
    {
      "name": "Meta Platforms, Inc.",
      "sym": "META",
      "price": 170.16
    },
    {
      "name": "Alphabet Inc.",
      "sym": "GOOG",
      "price": 2370.79
    }
  ]
}

Your decodable model should look like:

struct WebSocketMessage: Decodable {
    var stocks: [Stock]
    
    stuct Stock: Decodable {
        var name: String
        var sym: String
        var price: Double 
    }
}

Now, with your newly created WebSocketManager, you can subscribe to the receive publisher. You will now receive values over time.

Receiving messages:

var subscriptions = Set<AnyCancellables>()
let webSocketManager = WebSocketManager()

webSocketManager
    .receive()
    .sink(receiveValue: { webSocketMessage in
        // handle your messages here
    }, receiveCompletion: { completion in
        // handle completion here
    }.store(in: &subscriptions)

About

A lightweight WebSocket implementation in Swift using Combine.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages