Monday, October 21, 2013

Base 64 conversion iOS Decoding



Lot a time its being needed that we have to encrypt the data before we transmit over air, for this iOS also provides support for encoding and decoding the string or data we want to transmit or receive into a an encrypted format. Most common mode for encoding as I know is Base64, it similar to other coding except all the bits are converted to Number system having base as 64(Just as Binary is base 2, octal is base 8). iOS itself provides very useful and efficient methods to convert between Base64 and other encodings. I have just tried to give a model class which will simply allow user to call the methods and get the desired output. This following code snippet is for Decoding Base64-NSData or Base64-NSString into Normal NSString or NSData.
       

@implementation NSString (Base64)
#import "Base64.h"

#import 

#if !__has_feature(objc_arc)

#error This library requires automatic reference counting

#endif
 

+ (NSString *)stringWithBase64EncodedString:(NSString *)string

{

    NSData *data = [NSDatadataWithBase64EncodedString:string];

    if (data)

    {

        return [[selfalloc] initWithData:data encoding:NSUTF8StringEncoding];

    }

    returnnil;

}

 

- (NSString *)base64EncodedStringWithWrapWidth:(NSUInteger)wrapWidth

{

    NSData *data = [selfdataUsingEncoding:NSUTF8StringEncodingallowLossyConversion:YES];

    return [data base64EncodedStringWithWrapWidth:wrapWidth];

}

 

- (NSString *)base64EncodedString

{

    NSData *data = [selfdataUsingEncoding:NSUTF8StringEncodingallowLossyConversion:YES];

    return [data base64EncodedString];

}

 

- (NSString *)base64DecodedString

{

    return [NSStringstringWithBase64EncodedString:self];

}

 

- (NSData *)base64DecodedData

{

    return [NSDatadataWithBase64EncodedString:self];

}

 @end

       
 

Base 64 conversion iOS Encoding

Lot a time its being needed that we have to encrypt the data before we transmit over air, for this iOS also provides support for encoding and decoding the string or data we want to transmit or receive into a an encrypted format. Most common mode for encoding as I know is Base64, it similar to other coding except all the bits are converted to Number system having base as 64(Just as Binary is base 2, octal is base 8). iOS itself provides very useful and efficient methods to convert between Base64 and other encodings. I have just tried to give a model class which will simply allow user to call the methods and get the desired output. This code snippet is for Encoding normal NSData or NSString into Base64 NSString or NSData
       

#import "Base64.h"

#import 

#if !__has_feature(objc_arc)

#error This library requires automatic reference counting

#endif

 

@implementation NSData (Base64)

+ (NSData *)dataWithBase64EncodedString:(NSString *)string

{

    const char lookup[] =

    {

        99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 

        99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 

        99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 62, 99, 99, 99, 63, 

        52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 99, 99, 99, 99, 99, 99, 

        99,  0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 

        15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 99, 99, 99, 99, 99, 

        99, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 

        41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 99, 99, 99, 99, 99

    };

    

    NSData *inputData = [string dataUsingEncoding:NSASCIIStringEncodingallowLossyConversion:YES];

    long long inputLength = [inputData length];

    const unsigned char *inputBytes = [inputData bytes];

    

    long long maxOutputLength = (inputLength / 4 + 1) * 3;

    NSMutableData *outputData = [NSMutableData dataWithLength:maxOutputLength];

    unsigned char *outputBytes = (unsigned char *)[outputData mutableBytes];

 

    int accumulator = 0;

    long long outputLength = 0;

    unsigned char accumulated[] = {0, 0, 0, 0};

    for (long long i = 0; i < inputLength; i++)

    {

        unsigned char decoded = lookup[inputBytes[i] & 0x7F];

        if (decoded != 99)

        {

            accumulated[accumulator] = decoded;

            if (accumulator == 3)

            {

                outputBytes[outputLength++] = (accumulated[0] << 2) | (accumulated[1] >> 4);  

                outputBytes[outputLength++] = (accumulated[1] << 4) | (accumulated[2] >> 2);  

                outputBytes[outputLength++] = (accumulated[2] << 6) | accumulated[3];

            }

            accumulator = (accumulator + 1) % 4;

        }

    }

    

    //handle left-over data

    if (accumulator > 0) outputBytes[outputLength] = (accumulated[0] << 2) | (accumulated[1] >> 4);

    if (accumulator > 1) outputBytes[++outputLength] = (accumulated[1] << 4) | (accumulated[2] >> 2);

    if (accumulator > 2) outputLength++;

    

    //truncate data to match actual output length

    outputData.length = outputLength;

    return outputLength? outputData: nil;

}

 

- (NSString *)base64EncodedStringWithWrapWidth:(NSUInteger)wrapWidth

{

    //ensure wrapWidth is a multiple of 4

    wrapWidth = (wrapWidth / 4) * 4;

    

    constchar lookup[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

    

    long long inputLength = [self length];

    const unsigned char *inputBytes = [self bytes];

    

    long long maxOutputLength = (inputLength / 3 + 1) * 4;

    maxOutputLength += wrapWidth? (maxOutputLength / wrapWidth) * 2: 0;

    unsigned char *outputBytes = (unsigned char *)malloc(maxOutputLength);

    

    long long i;

    long long outputLength = 0;

    for (i = 0; i < inputLength - 2; i += 3)

    {

        outputBytes[outputLength++] = lookup[(inputBytes[i] & 0xFC) >> 2];

        outputBytes[outputLength++] = lookup[((inputBytes[i] & 0x03) << 4) | ((inputBytes[i + 1] & 0xF0) >> 4)];

        outputBytes[outputLength++] = lookup[((inputBytes[i + 1] & 0x0F) << 2) | ((inputBytes[i + 2] & 0xC0) >> 6)];

        outputBytes[outputLength++] = lookup[inputBytes[i + 2] & 0x3F];

        

        //add line break

        if (wrapWidth && (outputLength + 2) % (wrapWidth + 2) == 0)

        {

            outputBytes[outputLength++] = '\r';

            outputBytes[outputLength++] = '\n';

        }

    }

    

    //handle left-over data

    if (i == inputLength - 2)

    {

        // = terminator

        outputBytes[outputLength++] = lookup[(inputBytes[i] & 0xFC) >> 2];

        outputBytes[outputLength++] = lookup[((inputBytes[i] & 0x03) << 4) | ((inputBytes[i + 1] & 0xF0) >> 4)];

        outputBytes[outputLength++] = lookup[(inputBytes[i + 1] & 0x0F) << 2];

        outputBytes[outputLength++] =   '=';

    }

    else if (i == inputLength - 1)

    {

        // == terminator

        outputBytes[outputLength++] = lookup[(inputBytes[i] & 0xFC) >> 2];

        outputBytes[outputLength++] = lookup[(inputBytes[i] & 0x03) << 4];

        outputBytes[outputLength++] = '=';

        outputBytes[outputLength++] = '=';

    }

    

    if (outputLength >= 4)

    {

        //truncate data to match actual output length

        outputBytes = realloc(outputBytes, outputLength);

        return [[NSString alloc] initWithBytesNoCopy:outputBytes

                                              length:outputLength

                                            encoding:NSASCIIStringEncoding

                                        freeWhenDone:YES];

    }

    else if (outputBytes)

    {

        free(outputBytes);

    }

    returnnil;

}

 

- (NSString *)base64EncodedString

{

    return [selfbase64EncodedStringWithWrapWidth:0];

}

@end
       
 

Tuesday, May 7, 2013

Push Notifications in iPhone application - A complete walk through...

APNS(Apple Push Notification Services), It is one of the most innovative service provided by Apple, by which App-Developers are enabled to get in touch with their users personally.

The process seems very simple but the overall backend behind is somewhat a real Apple kind work.

You can add this your application using following steps:

STEP 1: In your application go to the AppDelegate.m file and in the method applicationDidFinishLaunching, add following code,

- (void)applicationDidFinishLaunching:(UIApplication*)application
{
 // Add registration for remote notifications
 [[UIApplication sharedApplication]
 registerForRemoteNotificationTypes:(UIRemoteNotificationTypeAlert |              UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound)];
// Clear application badge when app launches
 application.applicationIconBadgeNumber = 0;

///////////////////////////////////////
// Your Previous code resides here. //
///////////////////////////////////////
}
//Fetch and Format Device Token and Register Important Information to Remote Server


STEP 2: In your application go to the AppDelegate.m file  add following 2 Methods,

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)devToken {
 // code to register the device token to the provider
// Use this device token and send it to the Server which will use it to send messages to the device……………….
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
 NSLog(@"Error in registration. Error: %@", error);
}

STEP 3: In your application go to the AppDelegate.m file add following Method,
This method receives the notification.
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
 NSLog(@"remote notification: %@",[userInfo description]);
 NSDictionary *apsInfo = [userInfo objectForKey:@"aps"];
 NSString *alert = [apsInfo objectForKey:@"alert"];
 NSLog(@"Received Push Alert: %@", alert);
}



Multiline Text input or UItextView with Placeholder text

Hello All,

Hope all you awesome developers doing good and developing some cool projects, to let other people enjoy their lives (As being a developer, we Don`t have life ).

In one of my project, I got stuck to strange problem in which the requirement was such that I needed an Multiline inputfield having feature of placeholder text :( .

in iOS,
for multiline textInput we use - UITextView.
for textInput having placeholder feature - UITextfield.

Hope till now you might have got my problem. After 2 days of RnD(Googling ;)...), I got some links that helped me throughout.

I am hereby giving you the same coding which I used to implement the "Multiline text input with placeholder text property."

Hello, Now I am presenting the code snippet for u all, sorry for taking such long time.



#pragma mark - UItextViewDelegate
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    if( [text rangeOfCharacterFromSet:[NSCharacterSetnewlineCharacterSet]].location ==NSNotFound ) {
        return YES;
    }
    
    [textView resignFirstResponder];
    [scrollMessagescrollRectToVisible:CGRectMake(0, -110scrollMessage.frame.size.width,scrollMessage.frame.size.heightanimated:YES];
    returnNO;
}


- (BOOL) textViewShouldBeginEditing:(UITextView *)textView
{
    if(textView.tag == 0) {
        [scrollMessagescrollRectToVisible:CGRectMake(0110scrollMessage.frame.size.width,scrollMessage.frame.size.heightanimated:YES];
        textView.text = @"";
        textView.textColor = [UIColor blackColor];
        textView.tag = 1;
    }
    else {
        [scrollMessagescrollRectToVisible:CGRectMake(0110scrollMessage.frame.size.width,scrollMessage.frame.size.heightanimated:YES];
        textView.textColor = [UIColor blackColor];
    }
    returnYES;
}


Just give a couple of mins to understand this, and then just get ur answer!!!


Code will be available soon... :P

Adding Corner radius, Border width and shadow effect to any of the UI object in iPhone sdk

Hi friends,

Many a times when I was a newbie in iOS development, I had to face many problems regarding improving the look and feel of the UI elements. my designer too was a novice in mobile apps environment. At that time whenever I wanted  to develop a good looking user interface, I had to do a lot of RnD(a prestigious synonym for googling).

Below I will provide you some of the code snippets which I used at that time to make the interface look cool.

Note: You need to add QuartzCore framework to your project, along with also import <QuartzCore/QuartzCore.hin your file.

1. Snippet for adjusting the corner radius , or customising the rounded corner of UI elements.


   a. For setting the corner radius or making the corner of the UI element rounded you need just to add the following line to your existing code.
    
    myView.layer.cornerRadius = 5;
b. For setting the border width and border color of your UI element, please add the following lines to your existing code.


    myView.layer.borderWidth = 2;
    myView.layer.borderColor = [UIColorlightGrayColor].CGColor;
2. Snippet for adding shadow effects to UI elements.

Often you might have seen the iPhone screens having buttons and Images having a translucent shadow behind them, that effect you can have in 2 ways, either you must have a good designer who can make you an image holder image having the same effects. or the second approach is quite easy and also memory efficient, as you will be using only one UI-element(no extra image to show the shadow effect). 
Just add the following line of codes to your file and see the effect.
     myView.layer.shadowOpacity=0.8;
     myView.layer.shadowColor = [[UIColor lightGrayColor] CGColor];
     myView.layer.shadowOffset=CGSizeMake(0, 0); 
     myView.layer.shadowRadius=3;


Monday, May 6, 2013

Changing Text of Label Animated Using Blocks

Hi friends,

Many a times when I was a newbie in iOS development, I had to face many problems regarding improving the look and feel of the UI elements. my designer too was a novice in mobile apps environment. At that time whenever I wanted  to develop a good looking user interface, I had to do a lot of RnD(a prestigious synonym for googling).

Below I will provide you some of the code snippets which I used at that time to make the interface look cool.

Note: You need to add QuartzCore framework to your project, along with also import <QuartzCore/QuartzCore.hin your file.

1. Snippet for adjusting the corner radius , or customising the rounded corner of UI elements.


   a. For setting the corner radius or making the corner of the UI element rounded you need just to add the following line to your existing code.
    
    myView.layer.cornerRadius = 5;
b. For setting the border width and border color of your UI element, please add the following lines to your existing code.


    myView.layer.borderWidth = 2;
    myView.layer.borderColor = [UIColorlightGrayColor].CGColor;

2. Snippet for adding shadow effects to UI elements.

Often you might have seen the iPhone screens having buttons and Images having a translucent shadow behind them, that effect you can have in 2 ways, either you must have a good designer who can make you an image holder image having the same effects. or the second approach is quite easy and also memory efficient, as you will be using only one UI-element(no extra image to show the shadow effect). 
Just add the following line of codes to your file and see the effect.
     myView.layer.shadowOpacity=0.8;
     myView.layer.shadowColor = [[UIColor lightGrayColor] CGColor];
     myView.layer.shadowOffset=CGSizeMake(0, 0); 
     myView.layer.shadowRadius=3;

3.Snippet for changing the text of the UILabel animated using Blocks


[UIViewanimateWithDuration:1.3
                     animations:^{
                         lbl_MyLabel.alpha = 0.0f;
                         lbl_MyLabel.text = [self.dictFromLastView objectForKey:@"titleLbl"];
                         lbl_MyLabel.alpha = 1.0f;
                     }];


Adding Gradient effect to UILabel color


Below is the code snippet which when added to ur code will give a gradient effect to the UILabel. The output will be similar to the gradient effect in the UINavigationBar.


CAGradientLayer*gradient =[CAGradientLayer layer];
 gradient.frame = myView.bounds;//view fo the object whose graidient u are to set.
 gradient.colors =[NSArray arrayWithObjects:(id)[[UIColor blackColor]CGColor],(id)
                                [[UIColor whiteColor]CGColor], nil];
[myView.layer insertSublayer:gradient atIndex:0];