In swift, is there a way to add new data from second Realm bundle, without overwriting any existing data in the current Default Realm? - ios

Upon initial load of the app, the Bundled Realm (Realm1) is copied to the documents folder. Now that the bundled realm is set as the default realm, I am able update the bool property so that the table view can show marked and unmarked cells. However I am looking for a way to bundle a second realm (Realm2) with a later update, that will add new data to the existing default realm, but without overwriting the current default realm. I am currently working in swift 5 and Xcode 11.1, if that is helpful.
So far the only thing that I can think of is adding block of code to add new entries to the default realm. First the view will check to see what the count is of the realm, and if the count is the same as the original bundle, then it will add new data, if the count is equal to the initial bundle plus the new entries, then it will not add the new data again. I was hoping for a simpler solution that is cleaner in my opinion.
Ideally the end result would be a way to update the existing default realm, without overwriting the already edited content. Although I am rather new to using realm, any help in pointing me in the right direction for a solution would be greatly appreciated. Thanks.
Attached below is the current code I have implemented to load the default realm from the bundle.
let bundlePath = Bundle.main.path(forResource: "preloadedData", ofType: "realm")!
let defaultPath = Realm.Configuration.defaultConfiguration.fileURL!.path
let fileManager = FileManager.default
// Copy Realm on initial launch
if !fileManager.fileExists(atPath: defaultPath){
do {
try fileManager.copyItem(atPath: bundlePath, toPath: defaultPath)
print("Realm was copied")
} catch {
print("Realm was not coppied \(error)")
}
}
return true

Once you've created your default Realm on disk, if you want to read data from the bundled one, here's the code
let config = Realm.Configuration(
// Get the URL to the bundled file
fileURL: Bundle.main.url(forResource: "MyBundledData", withExtension: "realm"),
// Open the file in read-only mode as application bundles are not writeable
readOnly: true)
let realm = try! Realm(configuration: config)
and once you've read the data, you can switch back
var config = Realm.Configuration()
config.fileURL = config.fileURL!.deletingLastPathComponent().appendingPathComponent("\(some_realm_name).realm")
Realm.Configuration.defaultConfiguration = config
as far as not overwriting, ensure your objects use a unique primary key and when they are written, nothing will be overwritten as objects will a unique primary key will be added instead of overwriting.
class MyClass: Object {
#objc dynamic var my_primary_id = NSUUID().uuidString

I am adding an additional answer that's somewhat related to the first but also stands on it's own.
In a nutshell, once Realm connects to a data source, it will continue to use that data source as long as the objects are not released, even if the actual file is deleted.
The way around that is to encapsulate the Realm calls into an autorelease pool so that those objects can be released when the Realm is deleted.
Here’s an example:
This function adds a GameData object to the default.realm file.
func addAnObject() {
autoreleasepool {
let realm = try! Realm()
let testData = GameData()
testData.Scenario = "This is my scenario"
testData.Id = 1
try! realm.write {
realm.add(testData)
}
}
}
At this point, if you run the addAnObject code, your file will have a GameData object.
GameData {
Id = 1;
GameDate = (null);
Scenario = This is my scenario;
GameStarted = 0;
}
Then a function that delete’s the old realm, and copies the bundled realm to it’s place. This works because all of the interaction with Realm was enclosed in an autorelease pool so the objects can be released.
func createDefaultRealm() {
let defaultURL = Realm.Configuration.defaultConfiguration.fileURL!
let defaultParentURL = defaultURL.deletingLastPathComponent()
if let bundledRealmURL = self.bundleURL("default") {
do {
try FileManager.default.removeItem(at: defaultURL)
try FileManager.default.copyItem(at: bundledRealmURL, to: defaultURL)
} catch let error as NSError {
print(error.localizedDescription)
return
}
}
let migrationBlock : MigrationBlock = { migration, oldSchemaVersion in
//handle migration
}
Realm.Configuration.defaultConfiguration = Realm.Configuration(schemaVersion: 18, migrationBlock: migrationBlock)
print("Your default realm objects: \(try! Realm().objects(GameData.self))")
}
func bundleURL(_ name: String) -> URL? {
return Bundle.main.url(forResource: name, withExtension: "realm")
}
and please note that if you access Realm inside the class but outside an autorelease pool, Realm will refuse to 'let go' of it's objects.
Do do NOT do this!!
class ViewController: UIViewController {
var realm = try! Realm()

Related

Realm iOS: How to handle Client Reset

Basically, I want to handle a case where any device got SyncError with type ClientResetError then, want my device to re-login to realm again. but as per documentation, we have to closeRealmSafely before I login to realm again, but I am not sure how to close realm safely.
I am going through the doc (https://docs.realm.io/sync/using-synced-realms/errors#client-reset) to handle client reset error and found it's very confusing . I want help to understand about the following code.
First there is no method available to closeRealmsafely. Please help me understand how can I close the realm safely?
How can I backup and when I will use it? Should I skip the reset error because in documentation it's mentions if the client reset process is not manually initiated, it will instead automatically take place after the next time the app is launched, upon first accessing the SyncManager singleton. It is the app’s responsibility to persist the location of the backup copy if needed, so that the backup copy can be found later."
Below is the error handler sample code from the doc.
let syncError = error as! SyncError
switch syncError.code {
case .clientResetError:
if let (path, clientResetToken) = syncError.clientResetInfo() {
closeRealmSafely()
saveBackupRealmPath(path)
SyncSession.immediatelyHandleError(clientResetToken)
}
default:
// Handle other errors...
()
}
}```
Finally we figured out how to handle the client reset error. We have taken following steps To avoid the data loss incase user is offline and came online and got reset error.
Save the local realm to another directory
Invalidate and nil the realm
Initiate realm manual reset - Call SyncSession.immediatelyHandleError with clientResetToken passed and it will delete the existing realm from directory
Show client reset alert - This will intimate user to relaunch the app.
On next launch realm creates a fresh realm from ROS.
After new realm connects, restore the realm records (if any) from the old realm saved in backup directory above.
Delete the backup realm(old realm) from directory.
switch syncError.code {
case .clientResetError:
if let (path, clientResetToken) = syncError.clientResetInfo() {
// taking backup
backUpRealm(realm: yourLocalRealm)
// making realm nil and invalidating
yourLocalRealm?.invalidate()
yourLocalRealm = nil
//Initiate realm manual reset - Call `SyncSession.immediatelyHandleError` with `clientResetToken` passed and it will delete the existing realm from directory
SyncSession.immediatelyHandleError(clientResetToken)
// can show alert to user to relaunch the app
showAlertforAppRelaunch()
}
default:
// Handle other errors...
()
}
}```
The back up realm code look like this:
func backUpRealm(realm: Realm?) {
do {
try realm?.writeCopy(toFile: backupUrl)
} catch {
print("Error backing up data")
}
}
After doing this backup will be available at backup path. On next launch device will connect and download a fresh realm from ROS so after device connects restore the realm records from the backup realm saved in the backup path.
The restore merge backup code will look like this. place the below method when realm connects after relauch.The ```restoredRealm`` is fresh downloaded realm on launch
func restoreAndMergeFromBackup(restoredRealm: Realm?) {
let realmBackUpFilePath = isRealmBackupExits()
// check if backup exists or not
if realmBackUpFilePath.exists {
let config = Realm.Configuration(
fileURL: URL(fileURLWithPath: realmBackUpFilePath.path),
readOnly: true)
let realm = try? Realm(configuration: config)
guard let backupRealm = realm else { return }
//Get your realm Objects
let objects = backupRealm.objects(YourRealmObject.self)
try? restoredRealm?.safeWrite {
for object in objects {
// taking local changes to the downloaded realm if it has
restoredRealm?.create(YourRealmObject.self, value: object, update: .modified)
}
self.removeRealmFiles(path: realmBackUpFilePath.path)
}
} else {
debug("backup realm does not exists")
}
}
private func isRealmBackupExits() -> (exists: Bool, path: String) {
let documentsPath = URL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0])
let realmPathComponent = documentsPath.appendingPathComponent("your_backup.realm")
let filePath = realmPathComponent.path
let fileManager = FileManager.default
if fileManager.fileExists(atPath: filePath) {
return (true, filePath)
}
return (false, "")
}
private func removeRealmFiles(path: String) {
let realmURL = URL(fileURLWithPath: path)
let realmURLs = [
realmURL,
realmURL.appendingPathExtension("lock"),
realmURL.appendingPathExtension("realm"),
realmURL.appendingPathExtension("management")
]
for URL in realmURLs {
do {
try FileManager.default.removeItem(at: URL)
} catch {
debug("error while deleting realm urls")
}
}
}```
In our testing we have found that there is a backup made by realm automatically so we deleted it for safety purpose. the path argument you will get in the if let (path, clientResetToken) = syncError.clientResetInfo()
func removeAutoGeneratedRealmBackUp(path: String) {
do {
try FileManager.default.removeItem(at: URL(fileURLWithPath: path))
} catch {
debug("error while deleting realm backUp path \(path)")
}
}

Realm: Update pre-populated Database while keeping data from a specific field

I got a pre-populated database for my app. Occasionally I'm going to be updating this pre-populated database with new data.
The problem is that the object contains a boolean field called "completed". By default this field is false. When the user completes a certain task the object's boolean field becomes true.
I want to find a way when migrating to the new pre-populated database to keep that boolean field the same as before.
Here is the code I have so far
// copy over old data files
let defaultURL = Realm.Configuration.defaultConfiguration.fileURL!
let defaultParentURL = defaultURL.deletingLastPathComponent()
if let v0URL = bundleURL("database") {
//Delete if there's a file already
do {
try FileManager.default.removeItem(at: defaultURL)
print("Item Removed")
} catch {
print("error removing seeds: \(error)")
}
//Copy the database file to the directory
do {
try FileManager.default.copyItem(at: v0URL, to: defaultURL)
print("Item Copied")
}catch {
print("error copying seeds: \(error)")
}
}
// define a migration block
// you can define this inline, but we will reuse this to migrate realm files from multiple versions
// to the most current version of our data model
let migrationBlock: MigrationBlock = { migration, oldSchemaVersion in
migration.enumerateObjects(ofType: BookModel.className()) { oldObject, newObject in
// keep the old boolean completed value and assign it to the new one
let completed = oldObject!["completed"] as! Bool
newObject!["completed"] = completed
print(completed)
}
print("Migration complete.")
}
Realm.Configuration.defaultConfiguration = Realm.Configuration(schemaVersion: 5, migrationBlock: migrationBlock)
let realm = try! Realm()
return true
I am suspecting that my code does not work because before migration happens, I have already deleted my previous database (which contains the user's completed values). But how can I replace my previous database with the new one without delete-copy?
I can solve this with userDefaults but I would prefer the above solution.
Thank you in advance!

How to create a pre bundled realm file and upload data to it?

I am new to Realm and I want to ship a pre bundled Realm file my app, however the realm documentation is unclear to me on how to actually create a .realm file and also upload the desired pre bundled data to it. I have not been able to find any solution via SO, Google, or Youtube. Step-by-step instructions would be very helpful.
We're still looking at ways to officially make generating pre-populated Realms more easy. It's definitely a desired feature for the Realm Browser, but due to the way that Realm files require a migration when changing the schema, it's somewhat tricky to incorporate into a UI. It's definitely something we want to improve down the line.
At the moment, the Browser has a converter in it that can perform minimal data import like CSV files.
The Realm documentation is saying that the easiest way for you to produce a pre-populated Realm specific for your apps needs is to build a separate macOS app whose sole role is to generate the Realm file, pre-populate the data and then expose the resulting Realm file so you can copy it to your app.
The operation to do this is just like any normal Realm interaction (try! Realm() is what causes the file to actually be initially created), except you manually interact with the Realm file on disk upon completion.
I'm working on an app for an iOS conference, and the schedule data for the event is going to be stored in a Realm that is pre-bundled with the app when it ships.
Since I thought creating an extra macOS app would be overkill for an iOS app, I instead used iOS unit tests that would generate the pre-bundled Realm from scratch every time it was executed.
class Tests: XCTestCase {
func testGenerateNewDefaultRealm() {
let sources = [conferences, sponsors, conferenceDays] as [Any]
XCTAssert(generateDefaultRealm(named: "MyConferenceRealm.realm", sources: sources))
}
}
extension Tests {
public func generateDefaultRealm(named name: String, sources: [Any]) -> Bool {
// Create and configure the Realm file we'll be writing to
let realm = generateRealm(named: name)
// Open a Realm write transaction
realm.beginWrite()
// Loop through each source and add it to Realm
for source in sources {
if let objectArray = source as? [Object] {
for object in objectArray {
realm.add(object)
}
}
else if let objectDictionary = source as? [String : Object] {
for (_, object) in objectDictionary {
realm.add(object)
}
}
}
// Commit the write transaction
do {
try realm.commitWrite()
}
catch let error {
print(error.localizedDescription)
return false
}
// Print the file location of the generated Realm
print("=====================================================================")
print(" ")
print("Successfully generated at")
print(realm.configuration.fileURL!.path)
print(" ")
print("=====================================================================")
return true
}
public func generateRealm(named name: String) -> Realm {
let exportPath = NSTemporaryDirectory()
let realmPath = exportPath.appending(name)
// Delete previous Realm file
if FileManager.default.fileExists(atPath: realmPath) {
try! FileManager.default.removeItem(atPath: realmPath)
}
// Create new Realm file at path
let objectTypes: [Object.Type] = [Conference.self, ConferenceDay.self, SessionBlock.self, Event.self, Presentation.self,
Session.self, Location.self, Speaker.self, Sponsor.self, Venue.self]
let configuration = Realm.Configuration(fileURL: URL(string: realmPath), objectTypes: objectTypes)
let realm = try! Realm(configuration: configuration)
return realm
}
}
Running this unit test will generate a new Realm file in the NSTemporaryDirectory() directory of the Mac, and then feed in a set of Array and Dictionary objects of un-persisted Realm Object instances that are created each time the test is run. The location of the final Realm is then printed in the console so I can grab it and move it to the app bundle.

How to create a pre-prepared database and then load that data in my ios swift app?

I have a lot of data text in a couple of text files. How can I efficiently create a (Realm?) database with the data from those text files so I can add the database to my Xcode project and load the data into my app?
I have seen many tutorials on how to create Realm database with user entered data and then load it, but none with pre-made databases. I don't know if Realm is the right program to do this, but I looked really well.
I have downloaded the Realm Browser, but I could only view databases and couldn't find out how to create them easily.
EDIT:
I managed to create a database in Realm and put it in my xcode folder.
Then I try to load it like this, but let peoples doesn't contain the file's data, what am I missing:
let path = NSBundle.mainBundle().pathForResource("data", ofType: "realm")
var config = Realm.Configuration(fileURL: NSURL(fileURLWithPath: path!))
config.readOnly = true
let realm = try! Realm(configuration: config)
let peoples = realm.objects(Data)
Data is class which defines the schema:
class Data : Object {
dynamic var name = ""
dynamic var country = ""
dynamic var discription = ""
dynamic var image = ""
dynamic var cartoon = ""
dynamic var startYear = 0
dynamic var endYear = 0
}
An image of the realm file I'm trying to load:
Thanks for help!
Create a Sample Model:
final class ContentModel: Object {
dynamic var title = ""
dynamic var content = ""
dynamic var listName = ""
dynamic var id = 0
override static func primaryKey() -> String? {
return "id"
}
}
Create realm database:
let model = ContentModel()
model.id = 1
model.listName = "List Item 1"
model.title = "Title of content 1"
model.content = "Sample Text"
// Get the default Realm
let realm = try! Realm()
// Persist your data easily
try! realm.write {
realm.add(model)
}
Use this line to print the path to database:
print(Realm.Configuration.defaultConfiguration.fileURL!)
Now follow these steps (explained by realm)
Drag the new compacted copy of your Realm file to your final app’s Xcode Project Navigator.
Go to your app target’s build phases tab in Xcode and add the Realm file to the “Copy Bundle Resources” build phase.
At this point, your bundled Realm file will be accessible to your app. You can find its path by using NSBundle.main.pathForResource(_:ofType:).
Here's the code to get your bundled resource:
open class func getBundledRealm() -> Realm {
let config = Realm.Configuration(
// Get the URL to the bundled file
fileURL: Bundle.main.url(forResource: "default", withExtension: "realm"),
// Open the file in read-only mode as application bundles are not writeable
readOnly: true)
// Open the Realm with the configuration
let realm = try! Realm(configuration: config)
return realm
}
To Test your database:
let realm = RealmUtils.getBundledRealm()
// Read some data from the bundled Realm
let results = realm.objects(ContentModel.self)
for item in results {
print("Id: \(item.id)")
}
Realm Browser (as the name said) is just a browser.
for create pre-prepared database you should write some codes,
create empty database and insert data to it, then save it to Documents folder of simulator , comment insert code and copy generetated database from Documents folder, and add it as resource to your xCode project.
if your database static and you don't want to change anything on it simply just load your database with resource bundle path:
[[NSBundle mainBundle] pathForResource:#"nameOfFile" ofType:#"realm"];
but if you want to change some data you must copy it again to writable folder like Documents (for first time only)
I think what you are looking for is something like
https://github.com/Ahmed-Ali/JSONExport or JSONExportV in the Mac App Store
or
http://realmgenerator.eu/
If you already have your JSON, then these will generate the Realm Models that you can drop into your project. JSONExport supports way more languages and seems to work better for me with Swift. Just make sure you set the language to "Swift - Realm".

How can I take out a value as a string from RealmSwift?

I am developing an iOS app with RealmSwift by referring here. https://realm.io/docs/swift/latest/#in-memory-realms
And, what I don't understand is, how can I indicate the location(record and column) of the data in the realm file.
I've saved a realm file that named "DicData.realm" on the main folder where the same location as ViewController.swift is saved.
The data of DicData.realm is something like this:
1,face,423
2,rain,435
3,airplane,555
If I run the code below, it only printed like this: "results: Results ( )". It seems the filter method is just neglected. When I want to take out the word "airplane" and store in a variable as a string, how should I modify my code?
override func didMoveToView(view: SKView) {
func test()->Int {
let realm = try! Realm(configuration: Realm.Configuration(inMemoryIdentifier: "DicData"))
let results = realm.objects(DBData).filter("id == 3")
print("results: \(results)")
}
class DBData: Object {
dynamic var id = 0
dynamic var name = ""
dynamic var code = ""
}
You're referring here to the chapter of in-memory Realms and have setup your configuration to use those. An in-memory Realm is not a file. It lives exclusively in memory and is not actually written to disk.
If you've a prepared file, you want to bundle with your app, you need to make sure, that it is part of the Copy-Files Build Phase of the corresponding target of your Xcode project.
You can then copy the file from the app bundle initially via NSFileManager to a path, where the copy can be modified.
let defaultURL = Realm.Configuration.defaultConfiguration.fileURL!
let bundleURL = NSBundle.mainBundle().URLForResource("DicData", withExtension: "realm")!
do {
try NSFileManager.defaultManager().copyItemAtURL(bundleURL, toURL: defaultURL)
} catch {}
}

Resources