Realm Swift Database - Deployment and Usage Guide
Prerequisites
- macOS (for development) with Xcode 13.0 or later
- iOS 11.0+, macOS 10.13+, tvOS 11.0+, or watchOS 4.0+ (for deployment)
- Swift 5.0 or later
- Optional: MongoDB Atlas Account for cloud sync features
Installation
Option 1: Swift Package Manager (Recommended)
- In Xcode, go to File > Add Packages...
- Enter the package URL:
https://github.com/realm/realm-swift - Select the version or branch you want to use
- Click Add Package
Option 2: CocoaPods
- Add to your
Podfile:pod 'RealmSwift' - Run
pod install
Option 3: Carthage
- Add to your
Cartfile:github "realm/realm-swift" - Run
carthage update - Drag the built framework into your Xcode project
Option 4: Manual Installation
- Download the latest release from GitHub
- Extract the XCFramework
- Add the framework to your Xcode project
Configuration
Local Database (No Sync)
No configuration is required for local-only usage. Realm works out of the box with default settings.
With MongoDB Atlas Device Sync
- Create a MongoDB Atlas Account at mongodb.com/realm/register
- Create a new application in Atlas App Services
- Enable Device Sync for your application
- Download the configuration file (
realm-configuration.json) - Add the configuration file to your Xcode project
- Initialize Realm with the configuration:
let app = App(id: "your-app-id")
let config = app.currentUser.configuration(partitionValue: "your-partition")
let realm = try! Realm(configuration: config)
Encryption (Optional)
For encrypted databases, generate a 64-byte encryption key:
var key = Data(count: 64)
_ = key.withUnsafeMutableBytes { (pointer: UnsafeMutableRawBufferPointer) in
guard let baseAddress = pointer.baseAddress else {
fatalError("Failed to obtain base address")
}
SecRandomCopyBytes(kSecRandomDefault, 64, baseAddress)
}
let config = Realm.Configuration(encryptionKey: key)
let realm = try Realm(configuration: config)
Build & Run
Development
- Open your project in Xcode
- Build (Cmd+B) to compile
- Run (Cmd+R) to test on simulator or device
Testing
Realm includes comprehensive test suites. To run tests:
# Clone the repository
git clone https://github.com/realm/realm-swift.git
cd realm-swift
# Open the workspace
open RealmSwift.xcworkspace
# Select the desired test target
# Run tests using Cmd+U
Sample Usage
// Define your models
class Dog: Object {
@Persisted var name: String
@Persisted var age: Int
}
class Person: Object {
@Persisted(primaryKey: true) var _id: String
@Persisted var name: String
@Persisted var age: Int
@Persisted var dogs: List<Dog>
}
// Use the database
let realm = try! Realm()
let dog = Dog()
dog.name = "Rex"
dog.age = 1
try! realm.write {
realm.add(dog)
}
Deployment
iOS App Store
- Ensure your app meets App Store Review Guidelines
- Archive your application (Product > Archive)
- Upload to App Store Connect
- Submit for review
Enterprise Distribution
- Build for the appropriate device configuration
- Sign with your enterprise certificate
- Distribute via your enterprise distribution method (e.g., MDM, enterprise store)
macOS App Store
- Archive your application
- Upload to App Store Connect
- Submit for review
Note on Sync Features
If using MongoDB Atlas Device Sync, ensure your backend is properly configured and that your app has network connectivity for sync operations.
Troubleshooting
Common Issues
1. "Realm file is already open" Error
Cause: Multiple Realm instances trying to access the same file simultaneously.
Solution: Use a singleton pattern for Realm instances or ensure proper thread confinement.
class RealmManager {
static let shared = RealmManager()
private init() {}
lazy var realm: Realm = {
return try! Realm()
}()
}
2. Migration Issues
Cause: Schema changes between app versions without proper migration.
Solution: Implement migration blocks:
let config = Realm.Configuration(
schemaVersion: 2,
migrationBlock: { migration, oldSchemaVersion in
if oldSchemaVersion < 2 {
// Migration logic here
}
}
)
let realm = try! Realm(configuration: config)
3. Sync Connection Issues
Cause: Network connectivity problems or misconfigured sync settings.
Solution:
- Check your MongoDB Atlas configuration
- Verify network connectivity
- Check partition key configuration
- Review sync permissions in Atlas App Services
4. Performance Issues
Cause: Large datasets or inefficient queries.
Solution:
- Use proper indexing for frequently queried properties
- Implement pagination for large result sets
- Use
ResultsandListlazily - Consider file size limits and cleanup strategies
5. Encryption Key Issues
Cause: Using different encryption keys across app launches.
Solution: Persist the encryption key securely (e.g., in Keychain) and use the same key consistently.
Debug Logging
Enable debug logging for troubleshooting:
Realm.Configuration.defaultConfiguration = Realm.Configuration(
schemaVersion: 1,
migrationBlock: { migration, oldSchemaVersion in
// Migration logic
},
shouldCompactOnLaunch: { totalBytes, usedBytes in
// Compaction logic
return true
}
)
print("Realm configuration: \(Realm.Configuration.defaultConfiguration.fileURL!)")
Resources
- Documentation: mongodb.com/docs/atlas/device-sdks/sdk/swift/
- API Reference: mongodb.com/docs/realm-sdks/swift/latest/
- Community Forum: developer.mongodb.com/community/forums/tags/c/realm-sdks/58/swift/
- Stack Overflow: realm tag