Search This Blog

Friday, 9 January 2015

Difference between JSON and XML

Difference between JSON and XML

Hey guys! We come across JSON and XML many times while parsing data through Internet. 
So here I am to make you more aware when to use JSON and XML

In this post I am going to discuss the prime differences between JSON and XML

JSON

  • JavaScript Object  Notation.
  • It is used for data exchange over the internet which is human as well as machine readable.
  • Web services and APIs make use of JSON while making data available to public.
  • It is machine independent.
  • Light weight. So uses less data via transmission over the internet.
  • Can store only classical data types like numbers and text.
  • Easier to parse and read.
  • {} indicates JSON object and [] indicate JSON array.
  • Used to transmit data without formatting using primitive data formats.
example:
{
      "employees": [
        {
          "name": "Erik Cyrus",
          "gender": "male"
        },
        {
          "name": "Anny Sun",
          "gender": "female"
        }
      ]
}

XML

  • eXtensible Markup Language
  • Makes use of tags. These tags are user-defined. Hence the language is extensible.
  • Machine and human readable.
  • Used to define data structures and in webservices.
  • The tags are written within < > brackets.
  • We can define our own tags i.e. <name>, <birthdate>.
  • As it has starting and ending tags, it is slower than JSON while transmitting over the internet.
  • No different notations for arrays
  • It is better for sharing documents, because it allows datatypes like graphs, images, charts. 
example:

<employees>
      <employee>
        <name>Erik Cyrus</name>
        <gender>male</gender>
      </employee>
      <employee>
        <name>Anny Sun</name>
        <gender>female</gender>
      </employee>
</employees>

Hence both have their merits and demerits, it solely depends on the developer what to use what?

Hope you liked my article. Feel free to share your views.

Have a good day!

Monday, 28 May 2012

Localization in iPhone


Hello friends,

I am back after a long time. I would like to share the code of localizing your iPhone app. Its too simple if you see with minimal code.

Let's try it out.

Create a new project in xCode. now add a new file in the "Supporting Files" folder. The file type should be ".strings" and the name of the file should exactly be "Localizable.strings". Now keep thi sfile selected and go to file inspector. For going till there, go in View, select Utilities and select File inspector. a window will slide out from the right.

Now scroll down, there will be an option called localiztion. Below that there will be + and - sign for adding locale file for language of your choice.

Click on + sign add language of  your choice from the drop down. English will be by default. Let's add dutch. Now under Localizable.strings there will be two strings files, in english and in dutch.

Write the following lines in English Localizable.strings :

"name" = "My name is Riddhi Wala";
"work" = "I am a software engineer";
"friends" = "I ve got many friends - Sara, Dora";
"hobbies" = "Working, painting, reading, etc.";

REMEMBER: name, work, friends and hobbies are the keys which will remain same in all localized files. Only assigned values will change according to the language.

Now in Dutch Localizable Strings add following:

"name" = "Mijn naam is Riddhi Wala";
"work" = "Ik ben een software engineer";
"friends" = "Ik heb veel vrienden - Sara, Dora";
"hobbies" = "Werken, schilderen, lezen, enz.";

As you see the keys are same. If keys are wrong error will not be thrown but the value of the key will not be printed, instead the key will be printed.

Now  take four labels in view controller xib file and add their property in .h file. After that synthesize in .m file and then add the following piece of code in ViewDidLoad.

 The .h file code:


@interface ViewController : UIViewController

@property (retain, nonatomic) IBOutlet UILabel *label1;
@property (retain, nonatomic) IBOutlet UILabel *label2;
@property (retain, nonatomic) IBOutlet UILabel *label3;
@property (retain, nonatomic) IBOutlet UILabel *label4;

@end

The .m file code:

@implementation ViewController
@synthesize label1;
@synthesize label2;
@synthesize label3;
@synthesize label4;

- (void)viewDidLoad
{
    [super viewDidLoad];
    label1.text = [NSString stringWithString:NSLocalizedString(@"name", nil)];
    label2.text = [NSString stringWithString:NSLocalizedString(@"work", nil)];
    label3.text = [NSString stringWithString:NSLocalizedString(@"friends", nil)];
    label4.text = [NSString stringWithString:NSLocalizedString(@"hobbies", nil)];
   
}

BINGO!!

Try running your app when the language setting is English. Now change the language to Nederlands in simulator by going to Settings > General > International > Language > Nederlands. Then tap on Done button. And run your app again.  Note that if you change to any other language, your output will be in English unless you do not add the strings file of your desired language...

 
Geniet van! Een prettige dag!!


Friday, 4 May 2012

How to change title of button in Xcode

Hey friends,
Here is the code how to change the title of the UIButton:
In Your button action add the following code

-(IBAction)myButton:(UIButton *)sender{

NSString *str = (NSString *)[sender currentTitle];
if ([str isEqualToString:@"Play"]) 
{

[sender setTitle:[NSString stringWithString:@"Pause"] forState:UIControlStateNormal];[sender setImage:[UIImage imageNamed:@"Pause.png"] forState:UIControlStateHighlighted];
}
else
{

[sender setTitle:[NSString stringWithString:@"Play"forState:UIControlStateNormal];[sender setImage:[UIImage imageNamed:@"Play.png"] forState:UIControlStateNormal];


}

The explanation for the above code goes like, you must have seen in media player that while touching the Play button its text or image changes to pause the same thing can be achieved by the above code.

Good luck!!! :)

Thursday, 3 May 2012

code to record audio in iPhone

Hello friends,

I am quite new to iPhone technology but since I have started learning, I think its great fun. This is my first post so I would like to share something really interesting.

In this post I will explain you how to write a code to record audio and then play it.

First of all create a view based application in Xcode named AudioPlayer and then in AudioPlayerViewController.h write the following lines:

#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
#import <MediaPlayer/MediaPlayer.h>

@interface AudioPlayerViewController : UIViewController<AVAudioRecorderDelegate,
AVAudioPlayerDelegate> {

   
    AVAudioRecorder *audioRecorder;
    AVAudioPlayer *audioPlayer;
    int recordEncoding;
    enum  {
        ENC_AAC = 1,
        ENC_ALAC = 2,
        ENC_IMA4 = 3,
        ENC_ILBC = 4,
        ENC_ULAW = 5,
        ENC_PCM = 6,
    }encodingTypes;
   
    IBOutlet UISlider *volume;
    IBOutlet UILabel *amountOfVolume;
}
@property (nonatomic, retain) UISlider *volume;
@property (nonatomic, retain) UILabel *amountOfVolume;

-(IBAction) startRecording;
-(IBAction) stopRecording;

-(IBAction) startPlaying;
-(IBAction) stopPlaying;
@end


Now open AudioPlayerViewController.xib in the bottom part add 4 buttons and connect the "Touch Up Inside" event with the above actions.

Now open AudioPlayerViewController.m file and add the code block given below.

#import "AudioPlayerViewController.h"

@implementation AudioPlayerViewController
@synthesize volume, amountOfVolume;

-(void)viewDidLoad{
    //may be the file type supported will be ENC_PCM
    recordEncoding = ENC_PCM;
    [super viewDidLoad];
}

-(IBAction) startRecording{
    NSLog(@"start recording");
   
    if(audioRecorder){
        [audioRecorder release];
        audioRecorder = nil;
    }
   
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
   
    NSError *err = nil;
    [audioSession setCategory :AVAudioSessionCategoryRecord error:&err];
    if(err){
        NSLog(@"audioSession: %@ %d %@", [err domain], [err code], [[err userInfo] description]);
        return;
    }
    [audioSession setActive:YES error:&err];
    err = nil;
  
    NSMutableDictionary *recordSettings =
    [[NSMutableDictionary alloc] init];

    NSNumber *formatObject;
    // following are the conditions for checking encoding scheme used
    if (recordEncoding == ENC_PCM) {
               
        [recordSettings setObject:[NSNumber numberWithInt:kAudioFormatLinearPCM] forKey:AVFormatIDKey];
        [recordSettings setObject:[NSNumber numberWithFloat:44100.0] forKey:AVSampleRateKey];
        [recordSettings setObject:[NSNumber numberWithInt:2] forKey:AVNumberOfChannelsKey];
        [recordSettings setObject:[NSNumber numberWithInt:16] forKey:AVLinearPCMBitDepthKey];
        [recordSettings setObject:[NSNumber numberWithBool:NO] forKey:AVLinearPCMIsBigEndianKey];
        [recordSettings setObject:[NSNumber numberWithBool:NO] forKey:AVLinearPCMIsFloatKey];
       
    }
    else {
       
        switch (recordEncoding) {
            case (ENC_AAC):
                formatObject = [NSNumber numberWithInt:kAudioFormatMPEG4AAC];
                break;
            case (ENC_ALAC):
                formatObject = [NSNumber numberWithInt:kAudioFormatAppleLossless];
                break;
            case (ENC_IMA4):
                formatObject = [NSNumber numberWithInt:kAudioFormatAppleIMA4];
                break;
            case (ENC_ILBC):
                formatObject = [NSNumber numberWithInt:kAudioFormatiLBC];
                break;
            case (ENC_ULAW):
                formatObject = [NSNumber numberWithInt:kAudioFormatULaw];
                break;
            default:
                formatObject = [NSNumber numberWithInt:kAudioFormatAppleIMA4];
                break;
        }
       
        [recordSettings setObject:[NSNumber numberWithInt:kAudioFormatMPEG4AAC] forKey:AVFormatIDKey];
        [recordSettings setObject:[NSNumber numberWithFloat:44100.0] forKey:AVSampleRateKey];
        [recordSettings setObject:[NSNumber numberWithInt:2] forKey:AVNumberOfChannelsKey];
        [recordSettings setObject:[NSNumber numberWithInt:12800] forKey:AVEncoderBitRateKey];
        [recordSettings setObject:[NSNumber numberWithInt:16] forKey:AVLinearPCMBitDepthKey];
        [recordSettings setObject:[NSNumber numberWithInt:AVAudioQualityHigh] forKey:AVEncoderAudioQualityKey];
    }
   
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentDir = [paths objectAtIndex:0];

    NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/recordTest.caf",documentDir]];
    NSError *error = nil;
    audioRecorder = [[AVAudioRecorder alloc] initWithURL:url settings:recordSettings error:&error];

    // if instance of audio record is not created followoing if condition is fired
    if(!audioRecorder){
        NSLog(@"recorder: %@ %d %@", [err domain], [err code], [[err userInfo] description]);
        UIAlertView *alert =
        [[UIAlertView alloc] initWithTitle: @"Warning"
                                   message: [err localizedDescription]
                                  delegate: nil
                         cancelButtonTitle:@"OK"
                         otherButtonTitles:nil];
        [alert show];
        [alert release];

        return;
    }

    [audioRecorder setDelegate:self];

    if ([audioRecorder prepareToRecord]) {
        [audioRecorder record];
        audioRecorder.meteringEnabled = YES;

    }
    else {
        int errorCode = CFSwapInt32HostToBig([error code]);
        NSLog(@"Error: %@[%4.4s]", [error localizedDescription], (char*)&errorCode);
    }
   
    BOOL audioHWAvailable = audioSession.inputIsAvailable;
    if (! audioHWAvailable) {
        // this condition checks whether audio recording device is available or not

    }
   
    // start recording
    [audioRecorder recordForDuration:(NSTimeInterval) 10];

}

-(IBAction) stopRecording{
    NSLog(@"stop recording");
    [audioRecorder stop];
    NSLog(@"stop");
}

-(IBAction) startPlaying{
    NSLog(@"start playing");
    [audioPlayer release];
    audioPlayer = nil;
   
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    [audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];
   
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

/* if you are testing in device the file cannot be saved in the main bundle. so it should be saved in documentdirectory*/
    NSString *documentDir = [paths objectAtIndex:0];

 
 

    NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/recordTest.caf",documentDir]];
       
    NSError *error = nil;
   
    audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
    audioPlayer.numberOfLoops = 0;
    [audioPlayer play];


    //audioPlayer.volume = 100.0;
    // you can also change the volume according to the value of slider
    audioPlayer.volume = slider.value;

    NSLog(@"volume : %f",volume.value);
   
    NSLog(@"Playing");

}

- (void)audioRecorderDidFinishRecording:(AVAudioRecorder *) aRecorder successfully:(BOOL)flag
{
    // This code block is fired when we stop recording the audio....
    NSLog (@"audioRecorderDidFinishRecording:successfully:");
    // your actions here
   
}


-(IBAction) stopPlaying{
    NSLog(@"stop playing");
    [audioPlayer stop];
    NSLog(@"Stopped");
}



That's it. Now run your code and record your own interesting videos.
this is all for the day. See you next time with more interesting things. Good luck! ;)