Real-time Apps the SwiftUI way

Overview

Sync

Swift Package Manager Twitter: @nerdsupremacist

Sync

Sync is a proof of concept for expanding on the Magic of ObservableObject, and making it work over the network. This let's you create real-time Apps in which your Observable Objects are in sync across multiple devices. This has a lot of applications just as:

  • IoT Apps
  • Multi-Player Mini Games
  • etc.

As of right now Sync works out of the box using WebSockets, however, it's not limited to web sockets and it allows for multiple kinds of connections. Some possible connections could be:

  • Bluetooth
  • Multi-Peer
  • MQTT
  • etc.

The sky is the limit!

Warning: This is only a proof of concept that I'm using for experimentation. I assume there's lots and lots of bugs in there...

Installation

Swift Package Manager

You can install Sync via Swift Package Manager by adding the following line to your Package.swift:

import PackageDescription

let package = Package(
    [...]
    dependencies: [
        .package(url: "https://github.com/nerdsupremacist/Sync.git", from: "1.0.0")
    ]
)

Usage

If you have ever used Observable Object, then Sync will be extremely easy to use. For this example we will create an app with a Switch that everyone can flip on or off as they like. We will build this using SwiftUI, WebSockets and a Vapor Server. Final code available here.

Sync

For this we will need a few additional packages:

Let's start by building our shared ViewModel. This is easy, instead of using ObservableObject we use SyncableObject. And instead of Published we use Synced:

class ViewModel: SyncableObject {
    @Synced
    var toggle: Bool = false

    init() { }
}

This ViewModel needs to be both on your App codebase as well as on the Server codebase. I recommend putting it in a shared Swift Package, if you're feeling fancy.

Next stop is to create our server. In this example every client will be using the exact same ViewModel. So we're creating a Vapor application, and using syncObjectOverWebSocket to provide the object:

import Vapor
import SyncWebSocketVapor

let app = Application(try .detect())

let viewModel = ViewModel()
app.syncObjectOverWebSocket("view_model") { _ in
    return viewModel
}

try app.run()

For our SwiftUI App, we need to use two things:

  • @SyncedObject: Like ObservedObject, but for Syncable Objects. It's a property wrapper that will dynamically tell SwiftUI when to update the UI
  • Sync: A little wrapper view to start the remote session

Our actual view then uses SyncedObservedObject with our ViewModel

struct ContentView: View {
    @SyncedObject
    var viewModel: ViewModel

    var body: some View {
        Toggle("A toggle", isOn: $viewModel.toggle)
            .animation(.easeIn, value: viewModel.toggle)
            .padding(64)
    }
}

And in order to display it we use Sync, and pass along the Web Socket Connection:

struct RootView: View {
    var body: some View {
        Sync(ViewModel.self, using: .webSocket(url: url)) { viewModel in
            ContentView(viewModel: viewModel)
        }
    }
}

Developing for Web?

No problem. You can scale this solution to the web using Tokamak, and use the same UI on the Web thanks to Web Assembly. Here are the Web Assembly specific packages for Sync:

Here's a small demo of that working:

Sync

Contributions

Contributions are welcome and encouraged!

License

Sync is available under the MIT license. See the LICENSE file for more info.

You might also like...
This package is meant to make http request of an easy way inspiren in the architecture of Moya package

NetworkAgent This package is meant to make http request of an easy way inspiren in the architecture of Moya package. This package is 100% free of depe

The civilized way to write REST API clients for iOS / macOS
The civilized way to write REST API clients for iOS / macOS

The elegant way to write iOS / macOS REST clients Drastically simplifies app code by providing a client-side cache of observable models for RESTful re

The easy way to use sockets on Apple platforms

SwiftSocket SwiftSocket library provides as easy to use interface for socket based connections on server or client side. Supports both TCP and UDP soc

Music Room: a mobile app that offers a new way of experiencing music
Music Room: a mobile app that offers a new way of experiencing music

🎼 Music Room - 42 School Project 🎸 🤳🏻 Music Room is a mobile app that offers

EasyImplementationAlamoFire - An iOS project to demonstrate the usage of Alamofire in an efficient and organised way.

EasyImplementationAlamoFire Tutorial to demonstrate an efficient way of handling the APIs structure for your iOS Applications. Prerequisites Swift 5 X

Deal with query items, HTTP headers, request body and more in an easy, declarative way

Reusable system for complex URL requests with Swift. Deal with query items, HTTP headers, request body and more in an easy, declarative way. Check out our engineering blog to learn more!

Make it easier to observe network connectivity in SwiftUI.

ReachabilityX ReachabilityX is built using NWPathMonitor from Apple's Network framework to provide an easy way to observe the network changes for Swif

Showcasing simple SwiftUI and networking capabilities

CovidCounts CovidCounts is powered by SwiftUI. It allows a user to view COVID related data for different U.S. States. App Purpose This app is showcasi

WSChat OTVideo Chat With SwiftUI
WSChat OTVideo Chat With SwiftUI

WSChat-OTVideoChat !!! Be careful, this is not production-ready code. This is a quick and simple example of using some services. WSChat (using AWS IoT

Releases(1.1.0)
  • 1.0.2(Feb 23, 2022)

  • 1.0.1(Feb 21, 2022)

  • 1.0.0(Feb 21, 2022)

    Added

    • Added valueChange publisher to Synced, to listen for changes to the value
    • Added getter for connection to SyncedObject
    • Added support for getting a SyncedObbject from a parent SyncedObject via dynamic member lookup
    • Added SyncManager.reconnect method to restard connection
    • Added ReconnectionStrategy in order to attempt to resume the session after being disconnected

    Changed

    • Breaking: Renamed SyncedObject protocol to SyncableObject. To be consistent with ObservableObject
    • Breaking: Renamed SyncedObservedObject to SyncedObject. To be consistent with ObservedObject
    • Breaking: Projected Value of SyncedObject is of type now SyncedObject
    • Breaking: Renamed SyncableObject.manager to sync
    • Breaking: Renamed SyncableObject.managerWithoutRetainingInMemory to syncWithoutRetainingInMemory
    Source code(tar.gz)
    Source code(zip)
  • 0.1.1(Feb 21, 2022)

Owner
Mathias Quintero
Developer, Student, Spaghetti Code Enthusiast and Professional Swear Word Sayer.
Mathias Quintero
We need to observe the REAL reachability of network. That's what RealReachability do.

RealReachability We need to observe the REAL reachability of network for iOS. That's what RealReachability do. Why RealReachability? As we know, we al

Zhenwei Guan 3.1k Dec 13, 2022
A native, lightweight and secure time-based (TOTP) & counter-based (HOTP) password client built for iOS

A native, lightweight and secure time-based (TOTP) & counter-based (HOTP) password client built for iOS Built by Tijme Gommers – Buy me a coffee via P

Raivo OTP 770 Jan 8, 2023
Enable WebSocket in OPC DA/AE Server with JSON return, first time ever

WebSocket4OPC Enable WebSocket in OPC DA/AE Server with JSON return, first time ever DCOM was developed more than 2 decades ago, wich was the pillar o

null 13 Dec 14, 2022
A type-safe, high-level networking solution for Swift apps

What Type-safe network calls made easy Netswift offers an easy way to perform network calls in a structured and type-safe way. Why Networking in Swift

Dorian Grolaux 23 Apr 27, 2022
An open-source Swift framework for building event-driven, zero-config Multipeer Connectivity apps

PeerKit An open-source Swift framework for building event-driven, zero-config Multipeer Connectivity apps Usage // Automatically detect and attach to

JP Simard 861 Dec 23, 2022
StatusBarOverlay will automatically show a "No Internet Connection" bar when your app loses connection, and hide it again. It supports apps which hide the status bar and The Notch

StatusBarOverlay StatusBarOverlay will automatically show a "No Internet Connection" bar when your app loses connection, and hide it again. It support

Idle Hands Apps 160 Nov 2, 2022
A Swift Package that allows iOS apps to communicate with AltServer.

AltKit allows apps to communicate with AltServers on the same WiFi network and enable features such as JIT compilation.

Riley Testut 45 Sep 8, 2022
Control apps' wireless connectivity policy

AirKeeper This tweak replicates a feature in Chinese iPhone model by using Apple's own private APIs, which effectively writes to /var/preferences/com.

udevs 15 Dec 22, 2022
Approov Integration Examples 0 Jan 26, 2022
Codegeneration tool for isomorphic server and mobile Go apps with gRPC & Protobuf.

Codegeneration tool for isomorphic server and mobile Go apps with gRPC & Protobuf. Share code between your backend, Android & iOS app!

Kirill Biakov 17 Jun 25, 2020