Search code examples
iphoneiosipadplistepub

unable to read/write data to .plist file in iPhone


i am new to iPhone developer, i am creating ePub reader for reading ePub files.

I have plist in my iphone app and I want to read and write data to my .plist file, in which i am facing problem.

here is my code snippet,

Logic: first i am downloading an ePub file, .ePub file will be downloaded to this path

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
NSLog(@"basePath=%@",basePath);

output :- =/Users/krunal/Library/Application Support/iPhone Simulator/5.1/Applications/6B7FCD58-EDF9-44F4-8B33-5F3542536F92/Documents

now, i want to write name of Downloaded .ePubfile into file into my .plist

code:

NSMutableDictionary *data = [[NSMutableDictionary alloc] initWithContentsOfFile: basePath];

    [data setObject:[NSNumber numberWithInt:value] forKey:@"value"];

    [data writeToFile: plistPath atomically:YES];
    [data release];

i tried this, but i am unable to write in my .plist file.

Any Help Will be Appriciated.

Thanks In Advance !!


Solution

  • Did you mean:

    NSMutableDictionary *data = [[NSMutableDictionary alloc] initWithContentsOfFile: plistPath];
    

    ?


    untested code follows:

    Step 1: Copy the file to it's folder.

    NSError *error1;
    BOOL resourcesAlreadyInDocumentsDirectory;
    BOOL copied1;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *filePath1 = [documentsDirectory stringByAppendingString:@"/epub.plist"];
    
    resourcesAlreadyInDocumentsDirectory = [fileManager fileExistsAtPath:filePath1];
    
    if(resourcesAlreadyInDocumentsDirectory == YES) {
    
    } else {
    
        NSString *path1 = [[[NSBundle mainBundle] resourcePath] stringByAppendingFormat:@"/epub.plist"];
        copied1 = [fileManager copyItemAtPath:path1 toPath:filePath1 error:&error1];
    
        if (!copied1) {
            NSAssert1(0, @"Failed to copy epub.plist. Error %@", [error1 localizedDescription]);
        }
    }
    

    Step 2:Open it

    NSMutableDictionary* dict = [[NSMutableDictionary alloc] initWithContentsOfFile:filePath1]; 
    

    Step 3:Write data to it

    [dict setObject:[NSNumber numberWithInt:value] forKey:@"value"];
    [dict writeToFile:path atomically:YES];