Skip to content

Source code for Twilio Sync iOS and Android SDKs

License

Notifications You must be signed in to change notification settings

twilio/twilio-sync-sdk

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

23 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Twilio Sync SDK

CircleCI

Latest available SDK version:

  • Android Maven Central
  • iOS SwiftPM

Twilio Sync is Twilio's state synchronization service, offering two-way real-time communication between browsers, mobiles, and the cloud. Using Sync helps you avoid building all the real-time infrastructure to do this yourself.

This repo contains source code for the Twilio Sync SDKs for Android and iOS. See official documentation for more information about the Twilio Sync product.

Content

Using in your projects

Android

Android Sync SDK provides two modules:

  • sync-android-kt is targeted to be used from Kotlin apps. SyncClient exposes suspend methods to perform async operations. To use SyncClient from your Kotlin app, add the following dependency to your project:
dependencies {
    implementation "com.twilio:sync-android-kt:4.0.0"
}

See SyncClient documentation for details on how to create a SyncClient.

  • sync-android-java is targeted to be used from Java apps. SyncClientJava exposes methods which receive listeners to perform async operations. To use SyncClientJava from your Java app, add the following dependency to your project:
dependencies {
    implementation "com.twilio:sync-android-java:4.0.0"
}

See SyncClientJava documentation for details on how to create a SyncClientJava.

Compatibility

The Sync SDK now exposes dates using kotlinx.datetime.Instant. If you are targeting Android devices running below API 26, you will need to enable coreLibraryDesugaring to ensure compatibility. Follow the steps below:

android { 
    compileOptions { 
        coreLibraryDesugaringEnabled true 
    } 
}

dependencies {
    "com.android.tools:desugar_jdk_libs:1.2.2"
}

For more information on using kotlinx.datetime in your projects, visit the official documentation.

Example Usage

Here's an example of how to use the Sync SDK for Android:

    val syncClient = SyncClient(applicationContext) { requestToken() }

    // Create a new map
    val map = syncClient.maps.create()

    // Listen for item-added events flow
    map.events.onItemAdded
        .onEach { println("Item added: ${it.key}") }
        .launchIn(MainScope())

    // Declare custom data type
    @kotlinx.serialization.Serializable
    data class MyData(val data: Int)

    // Add 10 items to the map
    repeat(10) { index ->
        map.setItem("key$index", MyData(index))
    }

    // Read all items from the map
    for (item in map) {
        val myData = item.data<MyData>()
        println("Key: ${item.key}, Value: ${myData.data}")
    }

    // Remove the map
    map.removeMap()

iOS

Documentation

iOS SDK based on the code base from this repo is in beta state now. If you experience any issues - please report them to https://github.com/twilio/twilio-sync-sdk/issues

Swift Package Manager

To install the SDK using Swift Package Manager, follow these steps:

  1. Open your project in Xcode.
  2. Select File > Swift Packages > Add Package Dependency... .
  3. Enter https://github.com/twilio/twilio-sync-ios into the search field in the Choose Package Repository: dialog, then click Next .
  4. Make your versioning choice and click Next .
  5. Add the package to one of your targets and click Finish .

Example Usage

Here's an example of how to use the Sync SDK for iOS:

        import TwilioSync

        // Create a sync client
        let client = try await TwilioSyncClient.create { try await requestToken() }

        // Create a new map
        let map = try await client.maps.create()

        // Listen for item-added events flow
        let onItemAddedListener = Task {
            for await item in map.events.onItemAdded {
                print("Item added: \(item.key)")
            }
        }

        // Wait until subscription established
        _ = await map.events.onSubscriptionStateChanged.first { $0 == .established }
        
        // Add 10 items to the map
        for index in 0..<10 {
            _ = try await map.setItem(itemKey: "key\(index)", itemData: ["data": "value\(index)"])
        }

        // Read all items from the map
        for try await item in map {
            print("Key: \(item.key), Value:  \(item.data)")
        }

        // stop receiving events
        onItemAddedListener.cancel()

        // Remove the map
        try await map.removeMap()
    }

Build SDK

Download and setup Android SDK from Google if you don't have it yet

ANDROID_SDK_ROOT="$HOME/android-sdk"
LATEST_DIR="$ANDROID_SDK_ROOT/cmdline-tools/latest"

curl https://dl.google.com/android/repository/commandlinetools-mac-7302050_latest.zip --output /tmp/android-commandlinetools.zip
unzip -q -o /tmp/android-commandlinetools.zip -d /tmp
mv /tmp/cmdline-tools/* "$LATEST_DIR"

yes | "$LATEST_DIR/bin/sdkmanager" --licenses

# Put local.properties to the root of the twilio-sync-sdk repo.
echo "sdk.dir=$ANDROID_SDK_ROOT" >> "./local.properties"

Build Sync SDK for Android

From command line

./gradlew assembleRelease

From Android Studio

Open ./build.gradle in Android Studio and build as you would ordinarily.

Build Sync SDK for iOS

From command line

# Build kotlin native library
./gradlew sync-android-kt:assembleTwilioSyncLibReleaseXCFramework

# Build swift wrapper for the library
cd "./ios/TwilioSync"

xcodebuild archive \
    -project "TwilioSync.xcodeproj" \
    -scheme TwilioSync \
    -configuration "Release" \
    -destination "generic/platform=iOS" \
    -derivedDataPath DerivedData \
    -archivePath "output/archives/TwilioSync-iphoneos.xcarchive" \
    SKIP_INSTALL=NO \
    BUILD_LIBRARY_FOR_DISTRIBUTION=YES

xcodebuild archive \
    -project "TwilioSync.xcodeproj" \
    -scheme TwilioSync \
    -configuration "Release" \
    -destination "generic/platform=iOS Simulator" \
    -derivedDataPath DerivedData \
    -archivePath "output/archives/TwilioSync-iphonesimulator.xcarchive" \
    SKIP_INSTALL=NO \
    BUILD_LIBRARY_FOR_DISTRIBUTION=YES

xcodebuild -create-xcframework \
    -framework "output/archives/TwilioSync-iphoneos.xcarchive/Products/Library/Frameworks/TwilioSync.framework" \
    -framework "output/archives/TwilioSync-iphonesimulator.xcarchive/Products/Library/Frameworks/TwilioSync.framework" \
    -output "output/xcframeworks/TwilioSync.xcframework"

From xCode

Open ./ios/TwilioSync/TwilioSync.xcodeproj in xCode and build as you would ordinarily.

Build documentation

Android

For Kotlin

./gradlew packageDocs -PdocsSyncKotlin

For Java

./gradlew packageDocs -PdocsSyncJava

To see the built documentation open ./build/dokka/htmlMultiModule/index.html

iOS

  1. First Build Sync SDK for iOS
  2. Build documentation:
cd "./ios/TwilioSync"

xcodebuild docbuild -scheme TwilioSync \
   -destination "generic/platform=iOS" \
   -configuration "Release" \
   -derivedDataPath DerivedData

To see the built documentation open ./ios/TwilioSync/DerivedData/Build/Products/Release-iphoneos/TwilioSync.doccarchive

License

Copyright 2024 Twilio, Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.