How to make a copy of NSUserDefault and restore it again in Objective-c

0

I have not found anything with this topic, and I wanted to ask if anyone knows if it can be done and if that is how it is done.

I have my object:

NSUserDefaults *alertas;

and I want to make a copy of it in my database, in case a user deletes the app and later reinstalls it, being able to restore all the data without losing them.

Thank you.

    
asked by Jano 25.02.2017 в 21:01
source

3 answers

0

There are several topics here to address:

1 - How will you identify that user once you have uninstalled the app?

2 - Are you sure that this data should be stored in NSUserDefaults and not in CoreData?

Leaving aside this, if you want to save that object in your database I would do it by saving each of the values, then:

NSUserDefaults *alertas;

for(NSString* key in [[alertas dictionaryRepresentation] allKeys]){

  NSLog(@"Clave :%@", key);
  NSLog(@"Valor: %@",[alertas valueForKey:key]);

  [self sendKey:key andValue:[alertas valueForKey:key]];
}

- (void)sendKey:(NSString*)key andValue:(id)value {
  //Aquí implementas la función para enviar tus datos a servidor.
}

I hope it helps you;)

    
answered by 02.03.2017 в 09:28
0

It is necessary to identify each user . (Facebook, Twitter, User / Pass, etc)

The best option is to send the value to the server when the user modifies any key that exists in your object alerts. This way you will always have the data updated on the server.

    
answered by 02.03.2017 в 13:44
0

I do not recommend using the NSUserDefaults instance to save data since it is a section of the same application to save your internal configurations, such as region, languages, configuration of SDKs, etc. Consider using CoreData or some other ORM like Realm or Firebase, you could even save your own files and synchronize them with iCloud. link

If you still want to save the content of NSUserDefaults, the most practical thing is to take all the content and send it to your server.

NSUserDefaults* alertas;
// Transforma el objeto NSDictionary en un JSON NSData
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:[alertas dictionaryRepresentation] options:0 error:nil];
// Inicializa un string con JSON desde el NSData
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
// Luego puedes enviar el string completo a tu servidor, alli lo puedes parsear y guardar en tu base de datos o crear un fichero y guardarlo.

Keep in mind that if a user deletes your app, you must provide them with some identification method (e-mail login with password, login with Facebook, Login with Twitter, etc.) so that they can recover their data, but you must Put yourself in the case that you will not always be the same user on a device.

I hope the info helps you!

    
answered by 02.03.2017 в 21:49