tags:

views:

108

answers:

1

I'm trying to use the following code to persist the current list of local notifications. NSArray explicitly lists the kind of objects it will work with, which implies I can not use this with an array full of UILocalNotification objects. However, UILocalNotifications does implement NSCoding, which led me to believe there must be an easy way to serialize/deserialize this list of objects. Do I need to do the encoding and file persistence myself? Also, is there a way to get more information about why the write failed?

- (NSString*)getSavedNotifsPath {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];

    return [documentsDirectory stringByAppendingString:@"saved_notifs.plist"];
}

- (void)prepareToHide {
UIApplication* app = [UIApplication sharedApplication];
NSArray *existingNotifications = [app scheduledLocalNotifications];
if (! [existingNotifications writeToFile:[self getSavedNotifsPath] atomically:NO] ) {
    // alert
    [self showSomething:@"write failed"];
}
}
+1  A: 

First, change the code

return [documentsDirectory stringByAppendingString:@"saved_notifs.plist"];

to

return [documentsDirectory stringByAppendingPathComponent:@"saved_notifs.plist"];

stringByAppendingPathComponent: will ensure a slash (/) is included, if needed, before the file name.

NSArray can only save property list objects, which UILocalNotification is not. Instead, try using NSKeyedArchiver. For example:

- (void)prepareToHide {
   UIApplication* app = [UIApplication sharedApplication];
   NSArray *existingNotifications = [app scheduledLocalNotifications];
   NSString *path = [self getSavedNotifsPath];
   BOOL success = [NSKeyedArchiver archiveRootObject:existingNotifications toFile:path];
   if (! success ) {
      // alert
      [self showSomething:@"write failed"];
   }
}

Use NSKeyedUnarchiver to retrieve the array from the saved file.

Note: I have not actually tested this so I'm not 100% sure it will work. But give it a try and see what happens.

Kirby T
Cool, thanks Kirby! I didn't know NSKeyedArchiver existed. Paired that with NSKeyedUnarchiver and I got it working. Thanks!
Jeremy Mullin