Tuesday, March 5, 2013

Convert String to Base64 in iOS Tutorial


Convert String to Base64 in iOS Tutorial


To all the iOS Developers!! This time I would like to share one small but important stuff,

How to encode Plain Text to base64 string and 
again convert base64 string to our original Plain Text string.

So stay with me, and do it step by step by .. don't forget to drop me a message or comment.

Note : This Application Developed Using : iOS 6

PHASE - I (Create New Project)

So, Let's Fire Xcode!!

Go to File --> New --> Project

Now we can see a Window for selecting our application templet 

So make sure you select Application in iOS option on your Left hand side.
then select Single View Application as shown in below picture and Go for Next..



In this Next Window we need to put Our Project Details this way

Product Name : Base64Demo
Organization Name :RDCWorld
Company Identifier : com.rdcworld

Class Prefix :  (leave it blank for now)

Devices : iPhone

Note : Don't forget to Make Tick mark on "Use Automatic Reference Counting" option.



Go to Next --> Create.

Now you can see Xcode default dashboard with our newly created project .

For using base64 encoding we need to use "NSData+Base64" lib files in our application (say thanks to Matt Gallagher who made this easy)
so let's do it first.

1. download base64 lib file from here (http://projectswithlove.com/projects/NSData_Base64.zip)

you will find (NSData+Base64. {h,m} ) files in downloaded folder 



2. Just drag these two files to your project

NSData+Base64.h
NSData+Base64.m

this time our project structure is look like 



Note : Newly added files contains (autorelease etc) so we need to disable ARC for these.
do this way

2.1 Select Project (or click on Blue icon in Top Left side)

2. Go to --> Build Phases --> Compile Sources --> Click on Arrow to expend it 
3. now double click on NSData+Base64.m file and put "-fno-objc-arc" in popup window.



PHASE - II (Design UI)

We need to add  couple of UILabels and buttons, and a TextFields on our screen to get it work.

UITextField : for taking input message from user
UILabel : for showing converted results
UIButton : for convert our message stuff

So, Just open ViewController.xib file you can see default blank layout

1. Title bar : just drag UINavigation bar, double click on it , and give it title as "Base64 Encode-Decode" (we are using it as just simple Title bar )

2.drag UITextField, resize it and give it's Placeholder value as "enter message here" (you can find it on top right side in Attribute Inspector tab)

3. drag UILabels and buttons and put the text as shown in below picture 




PHASE - III (Create IBOutlets and IBAction )

We are going to create IBOutlet for UITextField,UILabel and IBAction method for UIButton.

Okay, Now select Assistant Editor on Top Right side




You can see our ViewController.xib (Left side) + ViewController.h (Right side) opened together.

1. Fist is First, Create IBOutlet for UITextField,UILabel

So now just Select UITextField --> Right Click on it 

Click on "New Referencing outlet" option and drag cursor to ViewController.h(right side) file, when your cursor is between @interface and @end you can see like this.



Now you will get Popup Window 

just put Name : "messageTextField" and click on Connect.



now you can see below code line in your ViewController.h file (in right side)

@property (weak, nonatomic) IBOutlet UITextField *messageTextField;

do the same for UILabels (one by one) i have selected both Labels to make you clear (where they are on layout). give the name "resultBase64Label" and "resultPlainTextLabel" respectively.



after adding IBOutlet for both Labels you can see two more line added to your header file.


@property (weak, nonatomic) IBOutlet UILabel *resultBase64Label;
@property (weak, nonatomic) IBOutlet UILabel *resultPlainTextLabel;


2. Now Create IBAction for UIButtons.

Right click on UIButton Convert to Base64 on Layout

Select "Touch Up Inside" in Send Event option and drag to header file this way



Now you will get Popup Window 
just put the Name : convertToBase64

and click on Connect button.



now do the same for next UIButton Convert to Plain Text and give the name in popup window as "convertToPlainText"

you can see two methods added in header file 

- (IBAction)convertToBase64:(id)sender;
- (IBAction)convertToPlainText:(id)sender;

Done!! now back to Standard Editor




PHASE - III (Writing Code)

Now Save app, and open ViewController.h file 


So Finally our ViewController.h file look like

-----------------------------------------------------------------------------------------------------------------------------------------
//
//  ViewController.h
//  Base64Demo
//
//  Created by RDC on 3/5/13.
//  Copyright (c) 2013 RDCWorld. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController

@property (weak, nonatomic) IBOutlet UITextField *messageTextField;

@property (weak, nonatomic) IBOutlet UILabel *resultBase64Label;
@property (weak, nonatomic) IBOutlet UILabel *resultPlainTextLabel;

- (IBAction)convertToBase64:(id)sender;
- (IBAction)convertToPlainText:(id)sender;


@end
-----------------------------------------------------------------------------------------------------------------------------------------


Now come to ViewController.m file , open it

1. import #import "NSData+Base64.h"

2. add synthesize (for all declared variable in header file with @property) just below to @implementation

@synthesize messageTextField;
@synthesize resultBase64Label;
@synthesize resultPlainTextLabel;

2. you can see two empty methods here

convertToBase64 and convertToPlainText

these methods we declared in header file using IBAction with Buttons

so update these two buttons code this way

- (IBAction)convertToBase64:(id)sender {
    
    //keypad go back
    [messageTextField resignFirstResponder];
    
    NSString *resultBase64String = [self base64Encode:messageTextField.text];
    resultBase64Label.text = resultBase64String;
}

- (IBAction)convertToPlainText:(id)sender {
    
    NSString *resultPlainString = [self base64Decode:resultBase64Label.text];
    resultPlainTextLabel.text = resultPlainString;
}


3. Now add Heart of the Application : two methods we need for encoding and decoding 
base64Encode and base64Decode

//convert plain text o base64
- (NSString *)base64Encode:(NSString *)plainText
{
    NSData *plainTextData = [plainText dataUsingEncoding:NSUTF8StringEncoding];
    NSString *base64String = [plainTextData base64EncodedString];
    return base64String;
}

//convert base64 to plain text
- (NSString *)base64Decode:(NSString *)base64String
{
    NSData *plainTextData = [NSData dataFromBase64String:base64String];
    NSString *plainText = [[NSString alloc] initWithData:plainTextData encoding:NSUTF8StringEncoding];
    return plainText;
}


So Finally our ViewController.m file look like

-----------------------------------------------------------------------------------------------------------------------------------------
//
//  ViewController.m
//  Base64Demo
//
//  Created by RDC on 3/5/13.
//  Copyright (c) 2013 RDCWorld. All rights reserved.
//

#import "ViewController.h"
#import "NSData+Base64.h"

@interface ViewController ()
@end

@implementation ViewController

@synthesize messageTextField;
@synthesize resultBase64Label;
@synthesize resultPlainTextLabel;

- (void)viewDidLoad
{
    [super viewDidLoad];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    
}

- (IBAction)convertToBase64:(id)sender {
    
    //keypad go back
    [messageTextField resignFirstResponder];
    
    NSString *resultBase64String = [self base64Encode:messageTextField.text];
    resultBase64Label.text = resultBase64String;
}

- (IBAction)convertToPlainText:(id)sender {
    
    NSString *resultPlainString = [self base64Decode:resultBase64Label.text];
    resultPlainTextLabel.text = resultPlainString;
}

#pragma mark - base64 methods

//convert plain text o base64
- (NSString *)base64Encode:(NSString *)plainText
{
    NSData *plainTextData = [plainText dataUsingEncoding:NSUTF8StringEncoding];
    NSString *base64String = [plainTextData base64EncodedString];
    return base64String;
}

//convert base64 to plain text
- (NSString *)base64Decode:(NSString *)base64String
{
    NSData *plainTextData = [NSData dataFromBase64String:base64String];
    NSString *plainText = [[NSString alloc] initWithData:plainTextData encoding:NSUTF8StringEncoding];
    return plainText;
}

@end
-----------------------------------------------------------------------------------------------------------------------------------------


Make sure your AppDelegate file code should be default 

Finally our AppDelegate.h file look like 

-----------------------------------------------------------------------------------------------------------------------------------------
//
//  AppDelegate.h
//  Base64Demo
//
//  Created by RDC on 3/5/13.
//  Copyright (c) 2013 RDCWorld. All rights reserved.
//

#import <UIKit/UIKit.h>

@class ViewController;

@interface AppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;

@property (strong, nonatomic) ViewController *viewController;

@end
-----------------------------------------------------------------------------------------------------------------------------------------


Finally our AppDelegate.m file look like 

-----------------------------------------------------------------------------------------------------------------------------------------
//
//  AppDelegate.m
//  Base64Demo
//
//  Created by RDC on 3/5/13.
//  Copyright (c) 2013 RDCWorld. All rights reserved.
//

#import "AppDelegate.h"

#import "ViewController.h"

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];    
    self.viewController = [[ViewController alloc] initWithNibName:@"ViewController" bundle:nil];
    self.window.rootViewController = self.viewController;
    [self.window makeKeyAndVisible];
    return YES;
}

//leave rest all empty methods..

@end
-----------------------------------------------------------------------------------------------------------------------------------------


Okay wrap it up this application. let's Run it.

Note : we could add so many things in this app (string validation on button click bla bla.. but  I wanted it to be simple as it can be) .

Here is the output 




Cheers!! we did it. It was so simple because Matt Gallagher did everything for us.
we just made it alive.

You can find complete project source code zip file here : Base64Demo


I Would love to here your thoughts !! 

No comments:

Post a Comment