NepCoder
NepCoder

Reputation: 439

How to pass the dictionary output value to the url in objective C?

I am working on a proof of concept app that scans a barcode and returns the barcode information as a UPC value(i.e. 9780596001612). I am confused on how to pass that return value to the url(I read some tutorials online but those doesn't seem to have what I am looking for). I have hardcoded the UPC value in the code and I am getting the right response but I want to be able to pass the return value from the barcode scan and pass that value to the url. I recently started working on Objective C and would greatly appreciate your help. Thank you.

- (void) onQRCodeScanned:(NSString*) result {
    NSString *theJSONString = [result description];
    NSError *theError = NULL;
    NSDictionary *theDictionary = [NSDictionary dictionaryWithJSONString:theJSONString  error:&theError];
    NSArray *results = [theDictionary objectForKey:@"decodedString"];
    //results returns 9780596001612 
    NSString *barcodeUrl = @"http://www.outpan.com/api/get_product.php?barcode=9780596001612";
    NSString *resp = [self makeRestAPICall: barcodeUrl];
}

Upvotes: 0

Views: 63

Answers (1)

Niall Paterson
Niall Paterson

Reputation: 3580

You need to format the string to include the barcode like this (I'm assuming the barcode is the first result of the results variable - it doesn't make sense in it's current format - and that first result does indeed exist):

NSArray *results = [theDictionary objectForKey:@"decodedString"];
NSString *barcode = [results firstObject];
NSString *barcodeUrl = [NSString stringWithFormat:@"http://www.outpan.com/api/get_product.php?barcode=%@",barcode];
NSString *resp = [self makeRestAPICall: barcodeUrl];

Notice how I using stringWithFormat: and then use %@ to represent a 'variable' as such, followed by the actual variable I want to include?

You can include primitive types using placeholders like %d (int), %c (char). You use %@ to represent an object, such as a NSString.

You can do this for any number of variables, but you'll get an error if the number of placeholders don't match the number of variables!

You may like reading this: String Format Specifiers

Upvotes: 1

Related Questions