Tuesday, April 1, 2014

Reading and Writing Values to a PList

Writing Values to a Plist:

-(int) saveBillingInformation:(NSString *)creditCardNumber setCCVNumber:(NSString*) ccvNumber setExpirationDate:(NSString*) expirationDate
{
   
    
    NSError *error;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); //1
    NSString *documentsDirectory = [paths objectAtIndex:0]; //2
    NSString *path = [documentsDirectory stringByAppendingPathComponent:@"data.plist"]; //3
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    if (![fileManager fileExistsAtPath: path]) //4
    {
        // 5
        NSString *bundle = [[NSBundle mainBundle] pathForResource:@"ccinfo" ofType:@"plist"];
        
        [fileManager copyItemAtPath:bundle toPath: path error:&error]; //6
    }
    
    NSMutableDictionary *data = [[NSMutableDictionary alloc] initWithContentsOfFile: path];
    
    //here add elements to data file and write data to file
    
    [data setObject:creditCardNumber forKey:@"creditCardNumber"];
    
    [data setObject:ccvNumber forKey:@"ccvCode"];

    [data setObject:expirationDate forKey:@"expirationDate"];
    
    [data writeToFile: path atomically:YES];
    
    return 1;
    

}

Reading a Value to a Plist:


-(NSMutableDictionary *) getPListBillingInfo
{
    
    NSError *error;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); //1
    NSString *documentsDirectory = [paths objectAtIndex:0]; //2
    NSString *path = [documentsDirectory stringByAppendingPathComponent:@"data.plist"]; //3
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    if (![fileManager fileExistsAtPath: path]) //4
    {
        // 5
        NSString *bundle = [[NSBundle mainBundle] pathForResource:@"ccinfo" ofType:@"plist"];
        
        [fileManager copyItemAtPath:bundle toPath: path error:&error]; //6
    }
    
    NSMutableDictionary *creditCardInfoDict = [[NSMutableDictionary alloc] initWithContentsOfFile: path];
    
    //load from savedStock example int value

    return creditCardInfoDict;

    // get the values from the NSMutableDictionary object
    

}

No comments:

Post a Comment