For a project I'm working on, I would like to save a few bytes of data to the users iPhone between launches of the application. I would like to do this so I can save some state and a few important numbers when the user terminates the app. I have thought about it, and the best place to do this seems like the AppDelegate.
- (void)applicationWillTerminate:(UIApplication *)application
{
// Called when the application is about to terminate.
// Save data if appropriate. See also applicationDidEnterBackground:.
/* this is where I want to begin the process of saving application data */
}
I have heard of writing objects (only a select few allowed such as NSString, NSDictionary, NSArray) to file, but can this be kept around between launches of the app, or does the data go away when the user terminates the app?
Question:
Is there a definitive way to write data to the users iPhone that will stick around after the application quits?
The most common approach is to persist whatever data or state you need when your app enters the background. Then the data will be there if the app is killed while in the background and the app is restarted.
How you store the data really depends on what the data is. Writing the data to a file in the app's sandbox is quite common. Small bits of data can also be stored in NSUserDefaults.
Related
I'm using NSUserDefaults in my iOS app to record some specific info about the user's receipt state.
I'd like to confirm:
If the user quits the app, will those defaults remain?
Are they global, for example I'm currently using the following line to either get or set them and across different methods. I just want to be certain the data within it persists - so if I set in method1 then later method2 I use the same line to get, it will have whatever I set in method1:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
If the user quits the app, will those defaults remain?
Yes, they are persistent.
Are they global?
Global in the sense of your whole app: Yes.
Global in the sense of across apps: No. They are in the app's sandbox.
From the NSUserDefaults documentation (see https://developer.apple.com/documentation/foundation/nsuserdefaults?language=objc)
With the exception of managed devices in educational institutions, a user’s defaults are stored locally on a single device, and persisted for backup and restore. To synchronize preferences and other data across a user’s connected devices, use NSUbiquitousKeyValueStore instead.
So for your first question the answer is yes.
Accordind to your second question, doc says:
At runtime, you use NSUserDefaults objects to read the defaults that your app uses from a user’s defaults database. NSUserDefaults caches the information to avoid having to open the user’s defaults database each time you need a default value. When you set a default value, it’s changed synchronously within your process, and asynchronously to persistent storage and other processes.
And even so, it declares that the class is thread safe, so you can be sure about persistent results (for your second answer).
Additionally with #Nikolai Ruhe answer.
if I set in method1 then later method2 I use the same line to get, it will have whatever I set in method1: NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
The UserDefaults class is thread-safe.
Two further points.
The uselessness of synchronize has grown up gradually through versions of iOS. It used to be essential; then advisable; then unnecessary. I can’t give you an exact timeline but a lot of it depends on how far back in iOS you want your app to work.
If you try to test some of these things in Xcode, beware. Up to and including iOS 11, synchronize does not write all the way to disk, but only puts data in a “lazy write” queue. Pressing the Stop button in Xcode (or pressing Run and allowing Xcode to stop the previous running app automatically) shuts everything down abruptly, more abruptly than anything a user can do, and the lazy writes are not written out, but lost. This is confusing while you are resting!! I filed a report on it and was told by Apple that (as Microfot would put it) “This behaviour is by design”.
But just to be clear: that second point does not present a problem for real apps in a real environment, only when you are trying to test “save and restart” scenarios. Waiting 5-10 seconds seems to be long enough for the flushed data to make it all the way to disk.
I have an App written in Swift that uploads statistics to my server. My question is simple and as follows: When is the best time to upload my statistics?
One approach I came up with was that I save all the statistics locally when the app quits. And when the app opens in the future, I upload the saved statistics and clear them.
The problem is applicationWillTerminate is not called sometimes, and data may be lost without being uploaded.
So what is the best way to solve my problem?
Thanks.
Similar to #jvrmed, I recommend saving your data locally whenever you want to record a stat. But I suggest pushing that data to your server when your application is about to resign active - i.e. when it is backgrounded.
func applicationWillResignActive(_ application: UIApplication) { }
Save your data locally whenever its generated. Once the app launches, send it and clear your local cache. You can use application:didFinishLaunchingWithOptions: to detect launching.
Its a good practice to cache information that you need to keep safe periodically, instead of all at once.
I have a Core Data app. It is like a let's say a News app. Each entry has name,id,date,publisher,detail etc. Main iOS app can have lots of News entries. I only want to show let's say first 3 news with the WatchOS app. Since getting news entries needs keyboard usage, I can't initiate transfers from the Watch side. What is the good strategy to share the data? I have thought following scenarios
Send Core Data files with WatchConnectivity transferFile
PROS: Easy
Huge amount of unnecessary data, may not have latest data if the changes aren't saved to context yet.
Whenever News is added send with WatchConnectivity before saving to CoreData.
PROS: Always same data,
CONS: Huge amount of unnecessary data, extra operations to save to new database
When the data is saved to Core Data, query last three objects and send them.
PROS: Small amount of data,
CONS: Need to convert NSManagedObject to another object first, may send same data
Could you help me to find a better way to sync iOS app with WatchOS app? Thanks.
I think the best approach would be background transfers using the application context. That has the following advantages:
You don't have to care about whether your watch app is running or not. When you add your data to the application context it gets added to to a transfer queue and whenever the watch app gets active, it receives the data.
Every time you add your three items, the old items get overwritten. So you always have only 3 items in the queue. That's ideal for a news app, where you don't want to bother your user with old news. So sending the same data several times is no problem, only the latest data "survives".
The only downside would be that you have to serialize your NSManagedObject. I don't know how complex your objects are, but if they are you could use library like HyperSync or Groot
So this is how you would then sync your phone with your app:
1. Set up the session:
if WCSession.isSupported() {
let session = WCSession.defaultSession()
session.delegate = self
session.activateSession()
}
Do this on both places: In your main app and also in the watch extension. If you are only sending data from your main app to the watch you do not need to set the delegate on the main app side.
2. Implement the delegate method:
func session(session: WCSession, didReceiveApplicationContext applicationContext: [String : AnyObject]) {
// deserialize the received data,
// store it in CoreData on your watch
// and update the UI
}
3. Send the data:
let dataDict = latestThreeNewsObjects.serializeToDictionary() // However you achieve this ;-)
do {
try WCSession.defaultSession().updateApplicationContext(dataDict as! [String : AnyObject])
} catch {
print("Cannot send data to watch: \(error)")
}
So then, every time you add new news items to your main app CoreData, fetch the latest three NSManagedObjects, serialize them into a dictionary and update your application context. This way the watch always has the latest 3 news when it gets active. When it already is active, the news get updated immediately.
One more thing: Before trying to send data to the watch, you should always check if the user has installed the app on his watch. WCSession has a property for that: watchAppInstalled. If the app is not installed, don't waste resources sending data into the abyss...
Here is the scenario in my app: I download data from a JSON File which I stock in Coredata WITHOUT saving it. If the users wants to keep the data, he clicks on a button, and I save the context.
My question is: if the user doesn't click on the button and I don't save the data, how long will the Context stay the way it is? Until the user closes the app? Or even goes to background?
I'm looking for the best way to manage it.
Assuming that you do nothing to change it and that the app receives no memory warnings, doesn't crash and doesn't go to the background - indefinitely. If the app goes to the background it may be killed at any time if the OS requires it, so you can rely on nothing.
Really you should save the context as soon as possible. If you need to, save to a different store file on disk, then if the user discards you can delete that file and if they save you can move it to replace the original file (or just update a config which says where the current valid file is located on disk).
I've implemented an iPhone application that has around 50k users. Switching from iOS7 to iOS8 a lot of these users have experienced a terrible feeling when they thought that they data get lost.
I've implemented the first-import behaviour that I thought was the one suggested by Apple
1) Users launch the App
2) iCloud, automatically, starts synching data previously stored on iCloud
3) At some point user get notified that data from iCloud is ready thanks to NSPersistentStoreUbiquitousTransitionTypeInitialImportCompleted
The problem is with 3) At some point:
Users that have to sync a lot of data need minutes to get the synch completed and in the meanwhile they think that their data is lost.
I really don't know how to let my users know that they have to wait to see their data synched, because I don't know when this operation starts.
I'm thinking about a possible solution:
During the first launch of the App, asking to the user if he wants to use iCloud. If he chooses to use it, building the database with iCloud options, so I know exactly that the synch is starting here (I suppose...)
I'm really not sure about how to implement this behaviour since I've always seen Core Data settings into the AppDelegate but to achieve this behaviour I suppose I need to move all the CoreData settings in a Controller.
What do you think about this solution? how are you working around this problem in you Apps?
Your idea is right, at least it is that what we do. But leave it in the appDelegate.
Differentiate between with iCloud and without iCloud when doing the "addPersistentStoreWithType". If you do it with iCloud options, it will directly start to build the local store which is a kind of a placeholder ( I'm sure you know that, but just to make my thoughts clear). As soon as this is done, the sync starts from iCloud. So this is the starting point I understood you were looking for.
You can watch that process using the notifications by NSPersistentStoreCoordinatorStoresDidChangeNotification and inform you user accordingly triggered by that notification.
If you look at "Reacting to iCloud Events" in the docs https://developer.apple.com/library/ios/documentation/DataManagement/Conceptual/UsingCoreDataWithiCloudPG/UsingSQLiteStoragewithiCloud/UsingSQLiteStoragewithiCloud.html#//apple_ref/doc/uid/TP40013491-CH3-SW5 there is a detailed desc.
To summarize, the event you're describing is part of the account transitions process. An account transition occurs when one of the following four events is triggered:
Initial import
the iCloud account used did change
iCloud is disabled
your application's data is deleted
During this event, Core Data will post the NSPersistentStoreCoordinatorStoresWillChangeNotification and NSPersistentStoreCoordinatorStoresDidChangeNotification notifications to let you know that an account transition is happening. The transition type we're interested in is NSPersistentStoreUbiquitousTransitionTypeInitialImportCompleted.
For information, I've moved all Core Data related code to my own Manager for simplicity and use it with a singleton design pattern. While setting up the singleton, I register the Manager for all relevant notifications (NSPersistentStoreDidImportUbiquitousContentChangesNotification, NSPersistentStoreCoordinatorStoresWillChangeNotification, NSPersistentStoreCoordinatorStoresDidChangeNotification, NSPersistentStoreCoordinatorWillRemoveStoreNotification).
I store several informations in my settings (NSUserDefaults or anything) like the last iCloud state (enabled, disabled, unknown), if the initial import is done or not, etc.
What I end up doing was having a prompt (UIAlertController or anything) to get a confirmation if the user wants to use iCloud or not. I have a displayICloudDialogAndForce:completion: method to do that and only do that if my iCloud state setting is unknown or I use the force parameter.
Then, after the user input, I call a setupCoreDataWithICloud: method, the iCloud boolean parameter depending on the user choice. I would then setup my Core Data stack, on the cloud or not according to the iCloud parameter.
If I'm setting up using iCloud, I would check my settings for the value of an iCloud imported key (boolean). If the value is NO, then I'm presenting a new modal to warn the user about the incoming import that could take some time.
I've registered my manager for different notifications and specially NSPersistentStoreCoordinatorStoresDidChangeNotification. In my storeDidChange: callback, I'm checking the transition type and if it's NSPersistentStoreUbiquitousTransitionTypeInitialImportCompleted, I'm changing the content of my modal to show the user that the import was successful and removing it a few seconds later, saving in my settings that the initial import is done.
- (void)storeDidChange:(NSNotification *)notification
{
NSPersistentStoreUbiquitousTransitionType transitionType = [notification.userInfo[NSPersistentStoreUbiquitousTransitionTypeKey] integerValue];
if (transitionType == NSPersistentStoreUbiquitousTransitionTypeInitialImportCompleted) {
[settings setDefaults:#(YES) forKey:kSettingsICloudImportedKey];
[ICloudModal dismissWithSuccess];
// ...
}
// Do other relevant things...
}