Thursday, 27 September 2012

iPhone Currency Converter using Google RESTful services

Google providing REST URI for currency calculator

 http://www.google.com/ig/calculator?hl=en&q=10USD=?INR

We have to pass the above two arguments to get JSON result

{lhs: "10 U.S. dollars",rhs: "536.912752 Indian rupees",error: "",icc: true}

The above returned JSON is invalid so convert into a valid JSON by adding '"' to lhs , rhs, error and icc.

How to handle JSON in iOS5 and later:

            NSJSONSerialization class used to convert JSON to Foundation objects like NSDictionary, NSArray etc and vice versa. It is only available iOS5 and above.

 NSDictionary* json = [NSJSONSerialization 
                          JSONObjectWithData:data 
                          options:kNilOptions 
                          error:&error];  //data is NSData sent from google server
now get the resulted json in NSDictionary then we can get the result by giving the key.

 NSString* convertedvalue = [json objectForKey:@"rhs"]; 

Difference between NSURLConnection and NSData initWithContentsOfURL :-

NSURLConnection is a asynchronous request by default , it will start a thread automatically and delegates are called from that thread. 
Also NSURLConnection has a convenience class method, sendSynchronousRequest:returningResponse:error:, to load a URL request synchronously.

NSData initWithCOntentsOfURL is a synchronous method call ,so it will block the thread.
Better use dispatch_async block to run the code in separate thread, once operation completed call the main thread.

find the iphone currency converter source code :-  https://github.com/karthikprabhuA/CurrencyConverter-GoogleRESTAPI

iphone
Currency converter 




- (IBAction)convertButtonCLicked:(UIButton *)sender {
    
     if([self.progressIndicator isAnimating]  == NO)
     {
    if(self.amountTxtField.text.length > 0 && self.fromTxtField.text.length >0 && self.toTxtField.text.length > 0)
    {
        [self.progressIndicator startAnimating];
        
        dispatch_queue_t downloadQueue = dispatch_queue_create("google downloader", NULL);
        
    dispatch_async(downloadQueue, ^{
        
        NSString* amount =self.amountTxtField.text;
        NSString *fromstr = self.fromTxtField.text ;
        NSRange fromrange ;
        fromrange.length = 3;
        fromrange.location = fromstr.length - 4;
        fromstr = [fromstr substringWithRange:fromrange];
        
        NSString *tostr = self.toTxtField.text ;
        NSRange torange ;
        torange.length = 3;
        torange.location = tostr.length -4;
        tostr = [tostr substringWithRange:torange];
        
        NSString *urlAddress = [[NSString alloc] initWithFormat:GOOGLERESTURL,[NSString stringWithFormat:@"%@%@",amount,fromstr],tostr];
        NSString* escapedUrlString =
        [urlAddress stringByAddingPercentEscapesUsingEncoding:
         NSUTF8StringEncoding];
    
        NSData* data = [NSData dataWithContentsOfURL
                        [NSURL URLWithString:escapedUrlString]];
        [self performSelectorOnMainThread:@selector(updateConvertedValue:) 
                               withObject:data waitUntilDone:YES];
        
    });
        dispatch_release(downloadQueue);
    }
    else {
        [self alertMessage:@"Enter all values !"];
    }
     }
}

-(void)updateConvertedValue: (NSData*)receivedData
{
    NSString *result = [[NSString alloc] initWithBytes:[receivedData bytes] length:[receivedData length] encoding:NSUTF8StringEncoding];
    NSError *error = NULL;
    //google is not sending valid JSOn so convert into valid JSON
    NSString *resultdata = result;
    resultdata = [resultdata stringByReplacingOccurrencesOfString:@"{" withString:@"{\""];
     resultdata = [resultdata stringByReplacingOccurrencesOfString:@"," withString:@",\""];
     resultdata = [resultdata stringByReplacingOccurrencesOfString:@":" withString:@"\":"];

    NSData* data = [resultdata dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary* json = [NSJSONSerialization 
                          JSONObjectWithData:data 
                          options:kNilOptions 
                          error:&error];
    
    NSString* convertedvalue = [json objectForKey:@"rhs"]; 
    if(error == nil)
        outputLabel.text = convertedvalue;
    else {
        outputLabel.text = @"conversion not available";
    }
     [self.progressIndicator stopAnimating];
    
}





4 comments:

  1. I wondered upon your blog and wanted to say that I have really enjoyed reading your blog posts. Any way I’ll be subscribing to your feed and I hope you post again soon.
    iOS Training in Chennai
    Android Training in Chennai
    php Training in Chennai

    ReplyDelete
  2. Codevian Technologies is a professional PHP development company. We provide our services and best results to our customers. We bring great websites and web application of every size to our clients. We transform your dream projects into reality. Codevian Technologies is the right place to hire php developers. Please feel free to call us on +91 9225108952 or contact by email at sales@codevian.com, if you require any additional information. Please visit our website www.codevian.com.com

    ReplyDelete