Thursday 16 October 2014

Register For Push Notification in iOS8

Register for Notification

 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions  
 {  
 #ifdef __IPHONE_8_0  
   UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:(UIRemoteNotificationTypeBadge  
                                              |UIRemoteNotificationTypeSound  
                                              |UIRemoteNotificationTypeAlert) categories:nil];  
   [[UIApplication sharedApplication] registerUserNotificationSettings:settings];  
 #else  
   UIRemoteNotificationType myTypes = UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound;  
   [[UIApplication sharedApplication] registerForRemoteNotificationTypes:myTypes];  
 #endif  
   return YES;  
 }  

Delegate Methods for Handle Push Notification


#pragma mark - Push Notification Methods

- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings  
 {  
   //register to receive notifications  
   [application registerForRemoteNotifications];  
 }

  
 //For interactive notification only  
 - (void)application:(UIApplication *)application handleActionWithIdentifier:(NSString *)identifier forRemoteNotification:(NSDictionary *)userInfo completionHandler:(void(^)())completionHandler  
 {  
   //handle the actions  
   if ([identifier isEqualToString:@"declineAction"]){  
   }  
   else if ([identifier isEqualToString:@"answerAction"]){  
   }  
 }

  
 -(void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken  
 {  
   NSLog(@“Device token : %@", deviceToken);  
 }

  
 - (void)application:(UIApplication*)application didFailToRegisterForRemoteNotificationsWithError:(NSError*)error  
 {  
   NSLog(@"Failed to get token, error: %@", error);  
 }

  
 - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo  
 {  
   NSLog(@“Your notification Info : %@", userInfo);  
 }

  
 -(void)handleRemoteNitification:(UIApplication *)application userInfo:(NSDictionary *)userInfo  
 {  
   NSLog(@“Your notification Info : %@", userInfo);  
 }  

Tuesday 1 July 2014

useful macro function for objective-c


for get log with class name, method name and line no

 #define DLog(fmt, ...) NSLog((@"%s [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__)  

for get UIColor

 #define COLOR(r,g,b) [UIColor colorWithRed:r/255.0 green:g/255.0 blue:b/255.0 alpha:1]  

is device type iPad or iPhone

 #define IS_iPad (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)  
 #define IS_iPhone ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone)  

is system iOS7 Or less

 #define IS_IOS7 (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_6_1)  

is device have 4inches display

 #define IS_4INCHES_DEVICE( fabs( ( double )[ [ UIScreen mainScreen ] bounds ].size.height - ( double )568 ) < DBL_EPSILON )  

for comparing system version

 #define SYSTEM_VERSION_EQUAL_TO(v)         ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedSame)  
 #define SYSTEM_VERSION_GREATER_THAN(v)       ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedDescending)  
 #define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)  
 #define SYSTEM_VERSION_LESS_THAN(v)         ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedAscending)  
 #define SYSTEM_VERSION_LESS_THAN_OR_EQUAL_TO(v)   ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedDescending)  

Friday 27 June 2014

Utility methods


Remove white space from string

 -(NSString*)trimString:(NSString *)theString  
 {  
      NSString *theStringTrimmed = [theString stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]];  
      return theStringTrimmed;  
 }  


get cache directory path

 -(NSString *)applicationCacheDirectoryString  
 {  
   NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);  
   NSString *cacheDirectory = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;  
   return cacheDirectory;  
 }  

for email validation

 -(BOOL)isValidEmailAddress:(NSString *)email  
 {  
   BOOL stricterFilter = YES;   
   NSString *stricterFilterString = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";  
   NSString *laxString = @".+@.+\\.[A-Za-z]{2}[A-Za-z]*";  
   NSString *emailRegex = stricterFilter ? stricterFilterString:laxString;  
   NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];  
   return [emailTest evaluateWithObject:email];  
 }  

string to date conversion

 - (NSDate *)stringToDate:(NSString *)dateString withFormate:(NSString *)format  
 {  
   NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];  
   [dateFormatter setDateFormat:format];  
   NSDate *date = [dateFormatter dateFromString: dateString];  
   return date;  
 }  

date to string conversion

 -(NSString *)DateToString:(NSDate *)date withFormate:(NSString *)format  
 {  
   NSDateFormatter *formatter = [[NSDateFormatter alloc] init];  
   [formatter setDateFormat:format];//2013-07-15:10:00:00  
   NSString * strdate = [formatter stringFromDate:date];  
   return strdate;  
 }  

get the age from birthdate

 -(NSString *)getAge:(NSDate *)birthDate  
 {  
   NSDate *dateA=birthDate;  
   NSDate *dateB=[NSDate date];  
   NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];  
   NSDateComponents *components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit  
                         fromDate:dateA  
                          toDate:dateB  
                         options:0];  
   NSLog(@"Difference in date components: %i/%i/%i", components.day, components.month, components.year);  
   return [NSString stringWithFormat:@"%i",components.year];  
 }  

get Image of view with its all subviews

 -(UIImage *)captureView:(UIView *)view  
 {  
   CGSize imageSize = CGSizeZero;    
   imageSize=CGSizeMake(view.bounds.size.width, view.bounds.size.height);  
   UIGraphicsBeginImageContext(imageSize);  
   CGContextRef context = UIGraphicsGetCurrentContext();  
   [view.layer renderInContext:context];  
   UIImage *screenShot = UIGraphicsGetImageFromCurrentImageContext();  
   UIGraphicsEndImageContext();  
   return screenShot;  
 }  

Sunday 24 November 2013

Save and Retrieve Custom Object from NSUserDefaults


If you have a custom class and save the object of class in NSUserDefaults you have the use initWithCoder and encodeWithCoder.

Example class :-

TestClass.h

 #import <Foundation/Foundation.h>  
   
 @interface TestClass : NSObject{  
   NSString *strTest;  
   NSMutableDictionary *dictTest;  
   int test;  
 }  
 @property(nonatomic,retain)NSString *strTest;  
 @property(nonatomic,retain)NSMutableDictionary *dictTest;  
 @property(nonatomic,assign)int test;  
   
 @end  

TestClass.m

 #import "TestClass.h"  
   
 @implementation TestClass  
   
 @synthesize strTest,dictTest,test;  
   
 -(id)initWithCoder:(NSCoder *)coder{  
   self=[[TestClass alloc]init];  
   if (self!=nil) {  
     self.strTest=[coder decodeObjectForKey:@"strTest"];  
     self.dictTest=[coder decodeObjectForKey:@"dictTest"];  
     self.test=[coder decodeIntegerForKey:@"test"];  
   }  
   return self;  
 }  
   
 -(void)encodeWithCoder:(NSCoder *)coder{  
   [coder encodeObject:self.strTest forKey:@"strTest"];  
   [coder encodeObject:self.strTest forKey:@"dictTest"];  
   [coder encodeInt:self.test forKey:@"test"];  
 }  
   
 @end  


Save and retrieve this TestClass object from NSUserDefaults.

Save Object

//create object

 TestClass *objTest=[[TestClass alloc]init];  

//set data

 objTest.strTest=@"Testing";  
 objTest.test=10;  
 NSMutableDictionary *dict=[[NSMutableDictionary alloc]init];  
 [dict setObject:@"Testing" forKey:@"Test"];  
 objTest.dictTest=dict;  

//save object to NSUserDefaults

 NSData *data=[NSKeyedArchiver archivedDataWithRootObject:objTest];  
 NSUserDefaults *userDefaults=[NSUserDefaults standardUserDefaults];  
 [userDefaults setObject:data forKey:@"customObject"];  
 [userDefaults synchronize];  

Retrieve Object

 NSUserDefaults *userDefaults=[NSUserDefaults standardUserDefaults];  
 NSData *dataSavedForObject = [userDefaults objectForKey:@"customObject"];  
 TestClass *objTest=[NSKeyedUnarchiver unarchiveObjectWithData:dataSavedForObject];  

Now you get the object of TestClass.


Saturday 23 November 2013

Save and Retrieve data from NSUserDefaults

Saving

 NSUserDefaults *userDefaults=[NSUserDefaults standardUserDefaults];  

// set value

 [userDefaults setBool:YES forKey:@"keyForBOOL"];  
 [userDefaults setDouble:10.5454 forKey:@"keyForDouble"];  
 [userDefaults setFloat:10.5 forKey:@"keyForFloat"];  
 [userDefaults setInteger:10 forKey:@"keyForInteger"];  
 [userDefaults setURL:[NSURL URLWithString:@"http://nsuserdefaults-in-iphone-sdk.blogspot.in/"]forKey:@"keyForURL"];  
 [userDefaults setObject:@"Hello" forKey:@"keyForObject"];  

// saving to user default

 [userDefaults synchronize];  

Retrieving

 NSUserDefaults *userDefaults=[NSUserDefaults standardUserDefaults];  

// get value from user default

 BOOL isYou = [userDefaults boolForKey:@"keyForBOOL"];  
 double varDouble = [userDefaults doubleForKey:@"keyForDouble"];  
 float varFloat = [userDefaults floatForKey:@"keyForFloat"];  
 NSInteger varInt = [userDefaults integerForKey:@"keyForInteger"];  
 NSURL *url = [userDefaults URLForKey:@"keyForURL"];  
 NSString *str = [userDefaults objectForKey:@"keyForObject"];  

Date comparison

For date comparison compare method use from NSDate.h,
this method return NSComparisonResult.

Custom method for date comparison:

 -(BOOL)isBetweenDate:(NSDate *)yourDate startingDate:(NSDate *)startDate endingDate:(NSDate *)endDate  
 {  
   if ([yourDate compare:startDate] == NSOrderedAscending)  
     return NO;  
   if ([yourDate compare:endDate] == NSOrderedDescending)  
     return NO;  
   return YES;  
 }  

Using this code for compare date:

 if ([self isBetweenDate:yourDate startingDate:startDate endingDate:endDate])  
   {  
     NSLog(@"Your date is between start and end date");  
   }  
   else{  
     NSLog(@"Your date is not between start and end date");  
   }  

Date formatting

There are some key that use for date formatting in objective-c:

For Time:

a (AM, PM)

//For Hour

h (1, 2, …., 12)
hh (01, 02, …., 12)
H (1, 2, …., 23, 24)
HH (01, 02, …, 23, 24)

//For minute

m(0,1,2,….,58,59)
mm(00,01,02,…,58,59)

//For second

s(0,1,2,….,58,59)
ss(00,01,02,…,58,59)

For Date:

d (1, 2, 3, …., 12, ….., 30, 31)
dd (01, 02, 03, ….., 12, …, 30, 31)

For Day:

e (1 to 7 days)
EEE (Sun, Mon, Tue, Wed, Thu, Fri, Sat)
EEEE (Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday)

For Month:

M (1, 2, …, 12)
MM (01, 02, …, 12)
MMM (Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec)
MMMM (January, February, March, April, May, June, July, August, September, October, November, December)

For Year:

yy (2 Digits year ex. 12)
YYYY (Full Year ex. 2012)

For Timezone:

z (for GMT Abbreviation of timezone)
zzzz (for GMT Name of timezone)

Methods for date to date formatting and conversion: 

//date to date

 -(NSDate *)convertDateToDate:(NSDate *) date  
 {  
    NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];  
    NSDate *newDate = [[[NSDate alloc] init] autorelease];  
    [formatter setDateFormat:@"yyyy-MM-d"];//use your format   
    NSString * strdate = [formatter stringFromDate:date];  
    newDate = [formatter dateFromString:strdate];  
    return newDate;  
 }  

this may return format of date like 2013-01-23