Friday, November 8, 2013

Easy Methods to Retrieve RESTful Data in Objective-C

-(NSMutableArray*) getItemsArray:(NSDictionary *)itemsDictionary
{

   // FOR METHODS NOT NATIVE TO OBJECTIVE-C SEE MY METHODS AS I USE THEM HERE: 
   // IE, convertToString (etc.)
    NSString* numberOfItems = [itemsDictionary objectForKey: @"numberOfDetails"];
int intNumberOfItems = [numberOfItems intValue];
NSNumber* price, *quantity;
    NSString* stringData, *stringItemNumber;
    NSMutableArray *itemsArray;

    NSLog(@"OrdersViewController: getItemsArray: Number of Details: %@", numberOfItems);
    NSLog(@"OrdersViewController: getItemsArray: intNumberOfItems: %i", intNumberOfItems);
    
    indivItem *item;
    NSDictionary* indivItemDictionary;
    
    itemsArray = [[NSMutableArray alloc] init];

    
    for (int i = 0; i < intNumberOfItems; i++) {
        
item = [[indivItem alloc] init];
stringItemNumber = [NSString stringWithFormat:@"%i", i];
        
NSLog(@"Item Index Number: %@", stringItemNumber);
        
        indivItemDictionary = [itemsDictionary objectForKey:stringItemNumber];
        
        stringData = [indivItemDictionary objectForKey:@"price"];
        NSLog(@"String Data Price Data of an Item: %@", stringData);
price = [self convertStringToNumber:stringData];
        NSLog(@"Price Data of an Item: %@", [price stringValue]);
item.price = price;
NSLog(@"Item's Price: %f", [item.price floatValue]);
        
stringData = [indivItemDictionary objectForKey:@"quantity"];
quantity = [self convertStringToNumber:stringData];
        item.quantity = quantity;
NSLog(@"Quantity: %i", [item.quantity integerValue]);
stringData = [indivItemDictionary objectForKey:@"itemName"];
item.itemName = stringData;
NSLog(@"Item's Name: %@", item.itemName);
     
[itemsArray addObject:item];
        
        
}
    
    return itemsArray;

    
}

-(NSDictionary*)getOrderDictionary:(NSString*)customerID
{
    
    
    NSString *urlString = @"http://www.website.com/test/restfulScriptCall.pl?";
    NSString *queryString = @"";
    queryString = [queryString stringByAppendingString:@"parametername="];
    queryString = [queryString stringByAppendingString:parametervalue];
    
    // Step 5:  Make the RESTful call.
    
    urlString = [urlString stringByAppendingString:queryString];
    
    urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
    
    
    NSLog(@"OrdersViewController URL String: %@", urlString);
    
    NSURL *url = [NSURL URLWithString:urlString];
    NSData *dataURL = [NSData dataWithContentsOfURL:url];
    NSDictionary *myDict = [NSJSONSerialization JSONObjectWithData:dataURL options:0 error:nil];

    return myDict;
    
    
    

}

No comments:

Post a Comment