Mobile SDKs
The Idiomark provides native mobile SDKs for both iOS and Android platforms. These SDKs enable you to integrate personality profiles, cloud synchronization, and AI inference directly into your mobile applications.
Overview
Both SDKs provide:
- Storage - Store and retrieve Idiomark personality files locally and from the cloud
- Sync - Real-time WebSocket synchronization across devices
- Inference - Generate personality-powered AI responses
- Security - Client-side encryption and secure keychain storage
- Reactive State - Modern reactive patterns (StateFlow for Android, Combine for iOS)
Requirements
- Android
- iOS
- Android API 26+ (Android 8.0 Oreo)
- Kotlin 1.9+
- Gradle 8.0+
- iOS 15.0+
- macOS 12.0+ (for Mac Catalyst)
- Swift 5.9+
- Xcode 14.0+
Installation
- Android
- iOS
Gradle (Kotlin DSL)
Add to your build.gradle.kts (module level):
dependencies {
implementation("xyz.idiomark:sdk:1.0.0")
}
Gradle (Groovy)
Add to your build.gradle:
dependencies {
implementation 'xyz.idiomark:sdk:1.0.0'
}
Maven
<dependency>
<groupId>xyz.idiomark</groupId>
<artifactId>sdk</artifactId>
<version>1.0.0</version>
</dependency>
Swift Package Manager
Add the Idiomark SDK to your Package.swift:
dependencies: [
.package(
url: "https://github.com/idiomark/mobile-sdk-ios.git",
from: "1.0.0"
)
]
Or add via Xcode:
- File > Add Packages...
- Enter:
https://github.com/idiomark/mobile-sdk-ios.git - Select version
1.0.0or later
CocoaPods
Add to your Podfile:
pod 'IdiomarkSDK', '~> 1.0'
Quick Start
- Android
- iOS
Initialize the SDK
import xyz.idiomark.sdk.IdiomarkSDK
import kotlinx.coroutines.launch
// In your Activity or Fragment
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// Start sync
IdiomarkSDK.startSync()
// Observe state
lifecycleScope.launch {
IdiomarkSDK.state.collect { state ->
updateConnectionUI(state.connected)
}
}
}
}
Load a Personality
lifecycleScope.launch {
val file = IdiomarkSDK.load("personality-id")
file?.let {
println("Loaded: ${it.personality?.voice?.tone?.primary}")
}
}
Generate a Response
lifecycleScope.launch {
val response = IdiomarkSDK.respond(
message = "What's your opinion on Kotlin?",
personalityId = "personality-id"
)
println(response)
}
Initialize the SDK
import SwiftUI
import IdiomarkSDK
@main
struct YourApp: App {
@StateObject private var sdk = IdiomarkSDK.shared
var body: some Scene {
WindowGroup {
ContentView()
}
.task {
await sdk.initialize()
}
}
}
Load a Personality
Task {
do {
let file = try await IdiomarkSDK.shared.load(id: "personality-id")
print("Loaded: \(file.personality?.voice.tone.primary ?? "Unknown")")
} catch {
print("Error: \(error)")
}
}
Generate a Response
Task {
do {
let response = try await IdiomarkSDK.shared.respond(
message: "What's your opinion on Swift?",
personalityId: "personality-id"
)
print(response)
} catch {
print("Error: \(error)")
}
}
Configuration
- Android
- iOS
The Android SDK uses a singleton pattern with default configuration:
// Configuration is handled internally with these defaults:
// - baseURL: "https://api.idiomark.protocol/storage"
// - syncURL: "wss://api.idiomark.protocol/ws"
// - enableSync: true
// - enableEncryption: true
// - timeout: 30000ms
// - maxRetries: 3
The iOS SDK uses a shared instance with configurable options:
let config = IdiomarkConfig(
baseURL: "https://api.idiomark.protocol",
apiKey: "your-api-key",
storagePath: FileManager.default.urls(
for: .documentDirectory,
in: .userDomainMask
).first?.appendingPathComponent("idiomark"),
enableSync: true,
enableEncryption: true,
syncInterval: 300, // 5 minutes
heartbeatInterval: 60, // 1 minute
maxRetries: 3,
timeout: 30,
debug: false
)
await IdiomarkSDK.shared.initialize(config: config)
Core API
Loading Personalities
- Android
- iOS
// Load by ID
val file = IdiomarkSDK.load("personality-id")
// Access personality data
file?.let {
println("Voice: ${it.personality?.voice?.tone?.primary}")
println("Domains: ${it.personality?.domains?.map { d -> d.name }}")
println("Confidence: ${it.personality?.voice?.confidence}")
}
// Load by ID
let file = try await IdiomarkSDK.shared.load(id: "personality-id")
// Access personality data
print("Voice: \(file.personality?.voice.tone.primary ?? "Unknown")")
print("Domains: \(file.personality?.domains.map { $0.name } ?? [])")
print("Confidence: \(file.personality?.voice.confidence ?? 0)")
Saving Personalities
- Android
- iOS
import xyz.idiomark.sdk.models.*
import java.util.Date
import java.util.UUID
lifecycleScope.launch {
val file = IdiomarkFile(
idiomark = "1.0.0",
id = UUID.randomUUID().toString(),
created = Date(),
updated = Date(),
metadata = IdiomarkMetadata(
entity = IdiomarkEntityType.HUMAN,
sources = listOf("twitter", "github"),
extractedAt = Date(),
sampleSize = 1000,
extractor = "my-app@1.0.0"
),
personality = personality,
signature = null
)
val result = IdiomarkSDK.save(file)
println("Saved: ${result.id}")
}
let profile = IdiomarkProfile(
idiomark: "1.0.0",
id: UUID().uuidString,
created: Date(),
updated: Date(),
metadata: IdiomarkMetadata(
entity: IdiomarkEntity(
name: "John Doe",
type: .human,
sources: ["twitter", "github"]
)
),
personality: personality
)
let profileManager = IdiomarkProfileManager()
try await profileManager.saveProfile(profile)
Generating Responses
- Android
- iOS
lifecycleScope.launch {
// Generate with personality ID
val response = IdiomarkSDK.respond(
message = "Tell me about yourself",
personalityId = "personality-id"
)
println("Response: $response")
}
// Or use the inference manager directly
IdiomarkSDK.inference.setPersonality(personality)
val response = IdiomarkSDK.inference.respond(
message = "Hello!",
personality = personality
)
Task {
// Generate with personality ID
let response = try await IdiomarkSDK.shared.respond(
message: "Tell me about yourself",
personalityId: "personality-id"
)
print("Response: \(response)")
}
// Or set active personality for multiple responses
let inference = IdiomarkInference(config: config)
inference.setPersonality(personality)
let response = try await inference.respond(
message: "Hello!",
personalityId: "personality-id"
)
Sync Control
- Android
- iOS
// Start automatic sync
IdiomarkSDK.startSync()
// Stop sync
IdiomarkSDK.stopSync()
// Observe sync state
lifecycleScope.launch {
IdiomarkSDK.state.collect { state ->
println("Connected: ${state.connected}")
println("Reconnecting: ${state.reconnecting}")
println("Pending events: ${state.pendingEvents}")
}
}
// Start automatic sync
try await IdiomarkSDK.shared.startSync()
// Stop sync
await IdiomarkSDK.shared.stopSync()
// Check connection state
if IdiomarkSDK.shared.isConnected {
print("Sync is active")
}
// Check if syncing
if IdiomarkSDK.shared.isSyncing {
print("Currently syncing...")
}
Reactive State
Both SDKs provide reactive state management for UI updates.
- Android
- iOS
Using StateFlow in Activities/Fragments
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// Observe state with lifecycle awareness
lifecycleScope.launch {
repeatOnLifecycle(Lifecycle.State.STARTED) {
IdiomarkSDK.state.collect { state ->
updateUI(state)
}
}
}
}
private fun updateUI(state: IdiomarkState) {
when {
state.connected -> binding.status.text = "Connected"
state.reconnecting -> binding.status.text = "Reconnecting..."
else -> binding.status.text = "Disconnected"
}
binding.pendingEvents.text = "${state.pendingEvents} pending"
}
}
Using StateFlow in Compose
@Composable
fun IdiomarkScreen() {
val state by IdiomarkSDK.state.collectAsState()
Column {
if (state.connected) {
Text("Connected", color = Color.Green)
}
Text("Pending: ${state.pendingEvents} events")
if (state.activePersonalityId != null) {
Text("Active: ${state.activePersonalityId}")
}
}
}
Using @Published Properties in SwiftUI
class ViewModel: ObservableObject {
@Published var isConnected = false
@Published var pendingEvents = 0
init() {
Task {
await IdiomarkSDK.shared.initialize()
await updateState()
}
}
func updateState() async {
self.isConnected = IdiomarkSDK.shared.isConnected
}
}
struct ContentView: View {
@StateObject var viewModel = ViewModel()
var body: some View {
VStack {
if viewModel.isConnected {
Text("Connected")
.foregroundColor(.green)
} else {
Text("Disconnected")
.foregroundColor(.red)
}
}
}
}
Callbacks
- Android
- iOS
// File change callback
IdiomarkSDK.onFileChanged = { file ->
println("File changed: ${file.id}")
}
// Sync complete callback
IdiomarkSDK.onSyncComplete = { result ->
if (result.success) {
println("Synced ${result.fileCount} files")
} else {
println("Sync failed: ${result.error}")
}
}
// Error callback
IdiomarkSDK.onError = { error ->
println("Error: ${error.message}")
}
// File change callback
IdiomarkSDK.shared.onFileChanged = { file in
print("File changed: \(file.id)")
}
// Sync complete callback
IdiomarkSDK.shared.onSyncComplete = { result in
if result.success {
print("Synced \(result.fileCount) files")
} else {
print("Sync failed: \(result.error ?? "Unknown error")")
}
}
// Error callback
IdiomarkSDK.shared.onError = { error in
print("Error: \(error.localizedDescription)")
}
Service Managers
Access lower-level service managers for advanced use cases.
Storage
- Android
- iOS
val storage = IdiomarkSDK.storage
// List files
val files = storage.list(ListRequest(limit = 50))
// Get specific file
val file = storage.get("file-id")
// Create file
val result = storage.create(file)
// Update file
val result = storage.update(file)
// Delete file
storage.delete("file-id")
// Check existence
val exists = storage.exists("file-id")
// Clear cache
storage.clearCache()
let storage = IdiomarkStorage(config: config)
// List files
let files = try await storage.list(limit: 50, offset: 0)
// Get specific file
let file = try await storage.get(id: "file-id")
// Create file
let created = try await storage.create(file: file)
// Update file
let updated = try await storage.update(id: "file-id", file: file)
// Delete file
try await storage.delete(id: "file-id")
// Check existence
let exists = try await storage.exists(id: "file-id")
// Local storage
let localFile = try await storage.read(id: "file-id")
let result = try await storage.write(file: file)
Sync
- Android
- iOS
val sync = IdiomarkSDK.sync
// Connect
sync.connect()
// Disconnect
sync.disconnect()
// Subscribe to channels
sync.subscribe("idiomark:file-id")
sync.subscribe("user:user-id")
// Unsubscribe
sync.unsubscribe("idiomark:file-id")
// Update presence
sync.updatePresence("online", mapOf("device" to "Android"))
// Pull sync
sync.syncPull(since = timestamp)
let sync = IdiomarkSync(config: config)
// Connect
try await sync.connect()
// Disconnect
await sync.disconnect()
// Subscribe to channels
await sync.subscribe(channels: ["idiomark:file-id", "user:user-id"])
// Pull sync
await sync.syncPull(since: Date(), fileId: nil)
// Check connection
if sync.isConnected {
print("Connected")
}
Inference
- Android
- iOS
val inference = IdiomarkSDK.inference
// Set active personality
inference.setPersonality(personality)
// Clear active personality
inference.clearPersonality()
// Generate response
val response = inference.respond(
message = "Hello!",
personality = personality
)
// Stream response (experimental)
inference.streamResponse(message, personality)
.collect { chunk ->
print(chunk.delta)
}
let inference = IdiomarkInference(config: config)
// Set active personality
inference.setPersonality(personality)
// Clear active personality
inference.clearPersonality()
// Generate response
let response = try await inference.respond(
message: "Hello!",
personalityId: "personality-id"
)
// Stream response
for try await chunk in inference.streamResponse(
message: "Hello!",
personalityId: "personality-id"
) {
print(chunk)
}
iOS-Specific Features
The iOS SDK includes additional features tailored for Apple platforms.
Profile Manager
let profileManager = IdiomarkProfileManager()
// Load all profiles
let profiles = try await profileManager.loadProfiles()
// Set active profile
try profileManager.setActiveProfile(id: profile.id)
// Get active profile
let active = profileManager.getActiveProfile()
// Search profiles
let results = profileManager.searchProfiles(query: "developer")
// Filter by entity type
let humans = profileManager.filterProfiles(by: .human)
// Sort by confidence
let sorted = profileManager.sortByConfidence(ascending: false)
Import/Export
// Import from JSON
let jsonData = try Data(contentsOf: fileURL)
let profile = try await profileManager.importProfile(from: jsonData)
// Export to JSON
let exported = try await profileManager.exportProfile(id: profile.id)
try exported.write(to: exportURL)
Encryption
let encryption = IdiomarkEncryptionService()
// Encrypt a profile
let encrypted = try await encryption.encryptProfile(profile)
// Decrypt a profile
let decrypted = try await encryption.decryptProfile(encrypted)
// Derive key from password
let (key, salt) = try encryption.deriveKey(
from: "secure-password",
salt: nil
)
Keychain Integration
let keychain = IdiomarkKeychainService.default
// Store auth token
try keychain.storeAuthToken("your-token-here")
// Retrieve token
let token = try keychain.getAuthToken()
// Check biometric availability
if keychain.isBiometricAvailable {
let type = keychain.biometricType // .faceID or .touchID
// Store with biometric protection
try keychain.setWithBiometrics(
key: .encryptionKey,
value: sensitiveData,
prompt: "Authenticate to access key"
)
}
Personality Injector
let injector = IdiomarkInjector(personality: personality)
// Inject personality into text
let input = "Hello, how are you?"
let output = injector.inject(into: input)
// Generate a response
let response = injector.generateResponse(to: input)
// With custom config
let config = IdiomarkInjectorConfig(
strength: 0.8,
enableEmoji: true,
enablePunctuation: true,
enableCapitalization: true
)
let injector = IdiomarkInjector(personality: personality, config: config)
Error Handling
- Android
- iOS
try {
val response = IdiomarkSDK.respond(
message = "Hello!",
personalityId = "personality-id"
)
} catch (e: StorageError.NetworkError) {
// Handle network error
println("Network error: ${e.message}")
} catch (e: StorageError.AuthenticationError) {
// Handle auth error
println("Authentication failed: ${e.message}")
} catch (e: StorageError.NotFoundError) {
// Handle not found
println("Profile not found: ${e.id}")
} catch (e: StorageError.ValidationError) {
// Handle validation error
println("Validation error: ${e.message}")
} catch (e: StorageError.RateLimitError) {
// Handle rate limit
println("Rate limited. Retry after: ${e.retryAfter}ms")
} catch (e: Exception) {
// Handle other errors
println("Error: ${e.message}")
}
do {
let response = try await IdiomarkSDK.shared.respond(
message: "Hello!",
personalityId: "personality-id"
)
} catch let error as IdiomarkError {
switch error {
case .fileNotFound(let id):
print("Profile not found: \(id)")
case .authenticationFailed(let message):
print("Authentication failed: \(message)")
case .network(let underlying):
print("Network error: \(underlying.localizedDescription)")
case .syncNotAvailable:
print("Sync service not available")
case .storageNotAvailable:
print("Storage service not available")
case .inferenceNotAvailable:
print("Inference service not available")
case .invalidConfig:
print("Invalid configuration")
}
} catch let error as IdiomarkProfileError {
switch error {
case .profileNotFound(let id):
print("Profile not found: \(id)")
case .validationFailed(let errors):
print("Validation failed: \(errors.joined(separator: ", "))")
case .saveFailed(let message):
print("Save failed: \(message)")
default:
print("Profile error: \(error.localizedDescription)")
}
} catch {
print("Unknown error: \(error.localizedDescription)")
}
Data Models
IdiomarkFile / IdiomarkProfile
- Android
- iOS
data class IdiomarkFile(
val idiomark: String, // Protocol version
val id: String, // Unique ID
val created: Date, // Creation time
val updated: Date, // Last update
val metadata: IdiomarkMetadata?,
val personality: Personality?,
val signature: String? // Digital signature
)
struct IdiomarkProfile: Codable, Identifiable {
let idiomark: String // Protocol version
let id: String // Unique ID
let created: Date // Creation time
let updated: Date // Last update
var metadata: IdiomarkMetadata?
var personality: Personality?
var signature: String? // Digital signature
}
Personality
- Android
- iOS
data class Personality(
val voice: Voice?, // Tone & style
val patterns: Patterns?, // Communication patterns
val domains: List<Domain>?, // Expertise areas
val values: List<Value>?, // Beliefs & values
val knowledge: Knowledge? // Topics & mentions
)
struct Personality: Codable {
var voice: Voice // Tone & style
var patterns: Patterns // Communication patterns
var domains: [Domain] // Expertise areas
var values: [Value] // Beliefs & values
var knowledge: Knowledge // Topics & mentions
}
Entity Types
- Android
- iOS
enum class IdiomarkEntityType {
HUMAN, // Real person
BRAND, // Company/brand
BOT, // Automated account
FICTIONAL // Fictional character
}
enum EntityType: String, Codable, CaseIterable {
case human = "human"
case brand = "brand"
case bot = "bot"
case fictional = "fictional"
}
Cross-Platform Considerations
API Parity
Both SDKs provide consistent APIs across platforms:
| Feature | Android | iOS |
|---|---|---|
| Storage | IdiomarkStorage | IdiomarkStorage |
| Sync | IdiomarkSync | IdiomarkSync |
| Inference | IdiomarkInference | IdiomarkInference |
| Reactive State | StateFlow | @Published |
| Coroutines/Async | Coroutines | async/await |
| Encryption | AES-GCM | CryptoKit AES-GCM |
Platform Differences
The iOS SDK includes additional Apple-specific features like Keychain integration, biometric authentication, and SwiftUI-friendly models.
- Android
- iOS
- Uses Kotlin coroutines and StateFlow
- OkHttp for networking
- Gson for JSON serialization
- ProGuard/R8 rules required
- Uses Swift async/await and Combine
- URLSession for networking
- Codable for JSON serialization
- Keychain for secure storage
- SwiftUI integration with
@Published
ProGuard / R8 (Android)
Add to your proguard-rules.pro:
# Idiomark SDK
-keep class xyz.idiomark.sdk.** { *; }
-keepclassmembers class xyz.idiomark.sdk.models.** { *; }
-dontwarn xyz.idiomark.sdk.**
Dependencies
- Android
- iOS
The SDK requires these dependencies (automatically included):
implementation("com.squareup.okhttp3:okhttp:4.12.0")
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.7.3")
implementation("com.google.code.gson:gson:2.10.1")
The SDK uses only Apple frameworks (no external dependencies):
- Foundation
- SwiftUI
- Combine
- CryptoKit
- NaturalLanguage
- LocalAuthentication
Testing
- Android
- iOS
Run tests with:
./gradlew test
For instrumented tests:
./gradlew connectedAndroidTest
Run tests with:
swift test --enable-code-coverage
Or via Xcode: Product > Test (Cmd+U)
Best Practices
- Reuse SDK instance - Both SDKs use singletons; don't create multiple instances
- Cache personality files - Don't reload on every request
- Handle offline gracefully - Both SDKs queue events when offline
- Set appropriate timeouts - Adjust based on your use case
- Use encryption - Enable encryption for sensitive profiles
- Validate profiles - Check
isValidbefore using personality data - Implement error handling - Always wrap calls in try/catch
Support
- Documentation: https://docs.idiomark.protocol
- Android Issues: GitHub Issues
- iOS Issues: GitHub Issues
- Discord: https://discord.gg/idiomark