Bundling a Realm with an App section - swift

I am trying to bundle a realm file with my app. I followed steps 1-5, but I am not clear on step 6. It says to copy the file back to the document folder, especially if it will be edited by the users.
Assuming, the copy statement goes inside the AppDelegate (similar to how it is done in the sample migration code), and the file is copied, what will happen the next time the app is launched? will it copy the file again, and overwrite it? Am I missing something?
Do I need to run it once before I ship the app, and then remove the code from the app delegate?
EDIT: this question is regarding realm-swift

If you bundle Realm file with your app it will be stored inside your app's bundle in Resources directory which is not writeable (because of the code signing). So if you want your users be able to change this data you have to copy this file to some directory with write access. Application’s Documents directory seems to be a good choice and it's also a default directory for default Realm.Configuration.
If it's an initial data for your app and you don't want to overwrite it each time your app launches, you can simply check if destination file exists and not copy your initial database in this case.
You can do it like this:
let initialURL = NSBundle.mainBundle().URLForResource("initial", withExtension: "realm")!
let defaultURL = Realm.Configuration.defaultConfiguration.fileURL!
if (!defaultURL.checkResourceIsReachableAndReturnError(nil)) {
do {
try NSFileManager.defaultManager().copyItemAtURL(initialURL, toURL: defaultURL)
} catch {
// Handle error here
}
}
let realm = try! Realm()

Adding to the above answer. Looks like currently the correct version of checking if realm file exists is: defaultURL.checkResourceIsReachable()

Related

How to write to a file in a project while the project is running? [duplicate]

Very new to MacOS development (as in, completely new). I've developed a MacOS app (SwiftUI / Swift) and now figuring out a very things related to deployment.
My app generates a text file, but I'd like to save it within the app's folder (or whatever it is called) - and not in a user specified folder, and read it when I want. I can read resources from the Assets.xcassets but I'd like to be able to save as well without making the user choose a location.
Is there a way I can write/read from the app folder (I'm struggling to explain as I'm very unfamiliar with this system)?
Yes you can create a directory inside your application support folder, name it with app’s bundle identifier or your company and store all files that are not accessible to the user there:
Use this directory to store all app data files except those associated
with the user’s documents. For example, you might use this directory
to store app-created data files, configuration files, templates, or
other fixed or modifiable resources that are managed by the app. An
app might use this directory to store a modifiable copy of resources
contained initially in the app’s bundle. A game might use this
directory to store new levels purchased by the user and downloaded
from a server. All content in this directory should be placed in a
custom subdirectory whose name is that of your app’s bundle identifier
or your company.
You should take some time and read the File System Basics documentation
do {
let applicationSupport = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first!
let bundleID = Bundle.main.bundleIdentifier ?? "company name"
let appSupportSubDirectory = applicationSupport.appendingPathComponent(bundleID,isDirectory: true)
try FileManager.default.createDirectory(at: appSupportSubDirectory, withIntermediateDirectories: true, attributes: nil)
print(appSupportSubDirectory.path) // /Users/.../Library/Application Support/YourBundleIdentifier
} catch {
print(error)
}

MacOS: How/where do I store a programmatically created file within my app folder?

Very new to MacOS development (as in, completely new). I've developed a MacOS app (SwiftUI / Swift) and now figuring out a very things related to deployment.
My app generates a text file, but I'd like to save it within the app's folder (or whatever it is called) - and not in a user specified folder, and read it when I want. I can read resources from the Assets.xcassets but I'd like to be able to save as well without making the user choose a location.
Is there a way I can write/read from the app folder (I'm struggling to explain as I'm very unfamiliar with this system)?
Yes you can create a directory inside your application support folder, name it with app’s bundle identifier or your company and store all files that are not accessible to the user there:
Use this directory to store all app data files except those associated
with the user’s documents. For example, you might use this directory
to store app-created data files, configuration files, templates, or
other fixed or modifiable resources that are managed by the app. An
app might use this directory to store a modifiable copy of resources
contained initially in the app’s bundle. A game might use this
directory to store new levels purchased by the user and downloaded
from a server. All content in this directory should be placed in a
custom subdirectory whose name is that of your app’s bundle identifier
or your company.
You should take some time and read the File System Basics documentation
do {
let applicationSupport = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first!
let bundleID = Bundle.main.bundleIdentifier ?? "company name"
let appSupportSubDirectory = applicationSupport.appendingPathComponent(bundleID,isDirectory: true)
try FileManager.default.createDirectory(at: appSupportSubDirectory, withIntermediateDirectories: true, attributes: nil)
print(appSupportSubDirectory.path) // /Users/.../Library/Application Support/YourBundleIdentifier
} catch {
print(error)
}

Open Downloads Directory With Finder Prompting User for Permission If Necessary

I'm building a BitTorrent client where I give the user an option, through a context menu, to open the containing directory of a torrent.
To do so, I tried using open(_) method of an NSWorkspace instance like so:
NSWorkspace.shared.open(directory)
where directory is an URL instance pointing to a directory, like so:
let directory = URL(fileURLWithPath: item.parentPath, isDirectory: true)
Here, item.parentPath is a String holding an absolute path.
Now, let me clear up that the code runs fine. It successfully opens up the directories I want inside Finder (since it's the default application for opening directories).
However, if the directory happens to be the Downloads directory of the user, it displays this prompt:
Again, this is alright since my application does not have permission to open the Downloads directory. However, I want to attempt to open the directory, asking for permission, just like any other application on macOS, like so:
I looked up in the docs and found this method of NSWorkspace: open(_:withApplicationAt:configuration:completionHandler:). I thought it was great since I could set the promptsUserIfNeeded property of an NSWorkspace.OpenConfiguration instance to true, which I believe should make my application politely ask for permission to open the directory if needed.
Here's my resulting code:
let url = URL(fileURLWithPath: item.parentPath, isDirectory: true)
let configuration: NSWorkspace.OpenConfiguration = NSWorkspace.OpenConfiguration()
configuration.promptsUserIfNeeded = true
let finder = NSWorkspace.shared.urlForApplication(withBundleIdentifier: "com.apple.finder")
// Open file with default application
NSWorkspace.shared.open([url], withApplicationAt: finder!, configuration: configuration)
Sadly, it's making no difference. I'm still getting the same dialog as shown in the first image.
I want to know two things:
What am I doing wrong?
How can I open a directory, prompting for permissions if necessary?
I am assuming you want this all to play nicely within the sandbox. You have two choices:
Use activateFileViewerSelecting(_:) or selectFile(_:inFileViewerRootedAtPath:). Either of these will prompt for permission, & once gained, you can return to using open(_:withApplicationAt:configuration:completionHandler:), if you so wish.
Use Security-Scoped Bookmarks and Persistent Resource Access.

read/write database path using sqlite.swift

I'm just starting out trying sqlite.swift and databases with swift. I have prepared a database with tables and preloaded with data. I wish to select data and insert data from within the app.
The problem is that I don't understand where (in my project) to put my database.db file in order for the app to find it.
my connection code:
let path = NSSearchPathForDirectoriesInDomains(
.documentDirectory, .userDomainMask, true
).first!
do {
db = try Connection("\(path)/database.db")
} catch {
db = nil
print ("Unable to open database")
}
In terms of where this file should go, I would suggest the “application support directory”. See File System Programming Guide: Where You Should Put Your App’s Files, which says:
Put user data in Documents/. User data generally includes any files you might want to expose to the user—anything you might want the user to create, import, delete or edit. For a drawing app, user data includes any graphic files the user might create. For a text editor, it includes the text files. Video and audio apps may even include files that the user has downloaded to watch or listen to later.
Put app-created support files in the Library/Application support/ directory. In general, this directory includes files that the app uses to run but that should remain hidden from the user. This directory can also include data files, configuration files, templates and modified versions of resources loaded from the app bundle.
Also see the iOS Storage Best Practices video.
The above is for iOS. If inquiring about macOS, see File System Programming Guide: The Library Directory Stores App-Specific Files.
But regardless of the OS, the technique for referencing the application support directory is largely the same:
do {
let fileURL = try FileManager.default
.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
.appendingPathComponent("database.db")
db = try Connection(fileURL.path)
} catch {
db = nil
print("Unable to open database: \(error)")
}

Date still in Core Data app after I delete the .sqlite files

I have (finally) managed to get prototype app using Core Data to persist to an sqlite file. Quitting and restarting I see the same data. So all seems well.
I want to now start from scratch again so I went to delete the sqlite persisted data. I set up it's location as :
open lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file.
let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
return urls[urls.count-1] as NSURL
}()
let url = self.applicationDocumentsDirectory.appendingPathComponent("TrainingDiary.sqlite")
which places the .sqlite files in ~/Library/Containers/uk.me.stevenlord.Core-Data-Binding/Data/Documents
There are four files in there: iChats, TrainingDiary.sqlite, TrainingDiary.sqlite-shm and TrainingDiary.sqlite-wal
I close my app. Delete all there files. When I reopen my app the full Core Data model is still there and when I look back in this directory the files are back.
What am I missing ?
EDIT:
I've figured out whats happening though I still don't quite understand why this is how it works. The above code specifies where the Core Data should be saved:
which places the .sqlite files in
~/Library/Containers/uk.me.stevenlord.Core-Data-Binding/Data/Documents/TrainingDiary.sqlite
This it does however I've now found that the app also saves the following
~/Library/Containers/uk.me.stevenlord.Core-Data-Binding/Data/Library/Application Support/Core Data Binding/Core_Data_Binding.sqlite
My XCode9 project is called "Core Data Binding". If I delete this file and start up my app I get an app with no data as expected.
So the persistent store is not going to where I specified. So still confused.
I'm missing something still. But something different