Search This Blog

Thursday 20 November 2014

iOS Phone No Validation



-(BOOL)checkValidation :(NSString *)phoneNo
{
    NSString *phoneRegex = @"((971)\\d{9})";
    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", phoneRegex];
    
    BOOL phoneValidates = [phoneTest evaluateWithObject:phoneNo];
    return phoneValidates;
    

}

Thursday 24 July 2014

Youtube Embeded not playing in landscape mode in iOS6 and above

Just Copy and paste below code in your AppDelegate

- (NSUInteger)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window {
    
    id presentedViewController = [window.rootViewController presentedViewController];
    NSString *className = presentedViewController ? NSStringFromClass([presentedViewController class]) : nil;
    
    if (window && [className isEqualToString:@"MPInlineVideoFullscreenViewController"]) {
        return UIInterfaceOrientationMaskAll;
    } else {
        return UIInterfaceOrientationMaskPortrait;
    }
    

}

Saturday 12 July 2014

Play Youtube video in webview with HTML

Copy and Paste below code and load in your webview:

NSURL *myURL =[NSURL URLWithString:@"http://www.youtube.com/v/zah99ETVOz4"];

NSString *embedHTML = @"<html><head><meta name = \"viewport\" content = \"initial-scale = 1.0, user-scalable = no, width = 212\"/></head><body style=\"background:#F00;margin-top:0px;margin-left:0px\"><div><object width=\"212\" height=\"172\"><param name=\"movie\" value=\"%@\"></param><param name=\"wmode\" value=\"transparent\"></param><embed src=\"%@\"type=\"application/x-shockwave-flash\" wmode=\"transparent\" width=\"320\" height=\"270\"></embed></object></div></body></html>";

NSString *html = [NSString stringWithFormat:embedHTML, myURL,myURL,myURL];





[YourWebView loadHTMLString:html baseURL:nil];

Monday 30 June 2014

Add Event into iphone Calendar

//Add Event kit framework
EventKit.framework
//import 
#import <EventKit/EventKit.h>

//Copy below code and enjoy

-(IBAction)AddEvent:(id)sender
{
    NSString *dateString = @"Jul 09,2014 00:00";
    
    //Create a formater
    NSDateFormatter *formater =[[NSDateFormatter alloc] init];
    [formater setDateFormat:@"MMM dd,yyyy HH:mm"];
    NSDate *startDate =[formater dateFromString:dateString];
    
    NSLog(@"current date %@",[NSDate date]);
    EKEventStore *store = [[EKEventStore alloc] init];
    [store requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error) {
        if (!granted) { return; }
        EKEvent *event = [EKEvent eventWithEventStore:store];
        event.title = @"My Birthday";
        event.startDate = startDate;//[NSDate date]; //today
        event.endDate = [event.startDate dateByAddingTimeInterval:60*60];  //set 1 hour meeting
        [event setCalendar:[store defaultCalendarForNewEvents]];
        NSError *err = nil;
        [store saveEvent:event span:EKSpanThisEvent commit:YES error:&err];
        NSString *savedEventId = event.eventIdentifier;  //this is so you can access this event later
    }];
    

}

Friday 6 June 2014

Convert mp3 to caf format


Open terminal and go to the folder where your mp3 file is placed then write below command and enter 

afconvert -f caff -d LEI16@44100 song.mp3 song.caf

Thats all 

Thursday 5 June 2014

Download Manager for iOS

Small effort by ideamakerz.
This download manager uses the iOS 7 NSURLSession api to download files.
  1. Can download files if app is in background.
  2. Can download multiple files at a time.
  3. It can resume interrupted downloads.
  4. User can also pause the download.
  5. User can retry any download if any error occurred during download.


You can download this amazing tool for your development from here.
Install in your device from here.


Tuesday 3 June 2014

How to right function in swift language

func whatsYourStatus (age:Int, name:String) ->(String)
{
    var answer=""
   
    if(age < 0)
    {
        answer = "you need to born first!"
    }
    else if(age < 13)
    {
        answer = "you are not ready for programing"
    }
    else if(age >= 13 && age <= 19)
    {
        answer = "you can start programing"
    }
    else if(age > 19 && age <= 25)
    {
        answer = "you are an expert of Objective-C"
    }
    else if(age > 25 && age <= 30)
    {
        answer = "you are not ready for swift"
    }
    else if(age > 30 && age <= 35)
    {
        answer = "you are an expert of swift"
    }
    else if(age > 35)
    {
        answer="you are retired , have time with your family"
    }
    return "\(name) \(answer)"
}

whatsYourStatus(45, "Kareem")

Wednesday 14 May 2014

SQLite DB Integration in iOS -- Basic Tutorial ,(In Process ....)

This Post is in under Development, it will be final soon....................

This post is the basic SQLite integration in iOS project for newcomers, if you are experienced developer then it will not be helpful for you :



To create database and manage tables you can add SQLite Manager Add-Ons in Firefox please follow the below guideline:




Open SQLite Manager from Firefox:



Creating new Database:

Creating a Table :





Optional: 
For SQLite DB this tool is also very helpful, if you wish to use just open sqlite file with Navicate:





Drag your SQLite database file into your project:


Make sure create group for any added folder is selected and  add to target your project as show in belowimage.



Copy Database into Document Directory:

You can call this method in didFinishLaunchingWithOptions in Appdelegate.m

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    
    //Copy Database into Document Directory
    [self copyDB];
}

-(void)copyDB
{
    //sample is the name of your database
    NSString *str = [[NSBundle mainBundle]pathForResource:@"sample" ofType:@"sqlite"];
    NSString *docpath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *destPaht = [docpath stringByAppendingPathComponent:@"sample.sqlite"];
    NSLog(@"databse path %@",destPaht);
    NSFileManager *mgr = [NSFileManager defaultManager];
    if (![mgr fileExistsAtPath:destPaht])
    {
        [mgr copyItemAtPath:str toPath:destPaht error:nil];
    }
    
}



//Below is class method for Select Query to get all records from table:
+(NSMutableArray *)GetAllRecords
{
    
    NSMutableArray *finalempArr =[NSMutableArray array];
    sqlite3 *database;
    if (sqlite3_open([Database_Path UTF8String], &database) == SQLITE_OK)
{
NSString *selectSql;
selectSql = [NSString stringWithFormat:@"SELECT * FROM records"];
sqlite3_stmt *statement;
if (sqlite3_prepare_v2(database, [selectSql cStringUsingEncoding:NSUTF8StringEncoding], -1, &statement, NULL) == SQLITE_OK)
{
while (sqlite3_step(statement) == SQLITE_ROW)
{
                NSMutableDictionary *empDic =[NSMutableDictionary dictionary];
                //here we get all column entries from table
                NSString *emp_id = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement,0)];
                NSString *emp_name = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement,1)];
                NSString *emp_age = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement,2)];
                NSString *emp_address = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement,3)];
                NSString *emp_cell = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement,4)];
                
                //adding entries in dictionary optioanl
                [empDic setValue:emp_id forKey:@"id"];
                [empDic setValue:emp_name forKey:@"name"];
                [empDic setValue:emp_age forKey:@"age"];
                [empDic setValue:emp_address forKey:@"address"];
                [empDic setValue:emp_cell forKey:@"cell"];
                
                [finalempArr addObject:empDic];
                empDic=nil;
}
sqlite3_finalize(statement);
}
else
{
NSLog(@"Error");
}
sqlite3_close(database);
        database=nil;
}
else
{
 NSLog(@"Database cant open");
}
return finalempArr;

}

You can call above method like this:

[DatabaseClass GetAllRecords];

You can download Sample SQLite Integration Code from  here.



Wednesday 16 April 2014

iPhone Screenshot Programatically

Below is the method to take screenshot :

- (UIImage *) screenshot
{
    UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, NO, [UIScreen mainScreen].scale);
    
    [self.view drawViewHierarchyInRect:self.view.bounds afterScreenUpdates:YES];
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

Saturday 12 April 2014

How to use NSArray in Macro


Here is the solution to define array in macro 

#define Alphabats @[@"A",@"B",@"C",@"D",@"E",@"F",@"G",@"H",@"I",@"J",@"K",@"L",@"M",@"N",@"O",@"P",@"Q",@"R",@"S",@"T",@"U",@"V",@"W",@"X",@"Y",@"Z"]

How to access this array in your code :

NSMutableArray *charArray =[NSMutableArray arrayWithArray:Alphabats];

Thursday 10 April 2014

Check Date Format in iPhone

This method is useful to check which date formate is selected in iphone etither 24 hours or 12 hours

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setLocale:[NSLocale currentLocale]];
[formatter setDateStyle:NSDateFormatterNoStyle];
[formatter setTimeStyle:NSDateFormatterShortStyle];
NSString *dateString = [formatter stringFromDate:[NSDate date]];
NSRange amRange = [dateString rangeOfString:[formatter AMSymbol]];
NSRange pmRange = [dateString rangeOfString:[formatter PMSymbol]];


Bool HourFormate24 = (amRange.location == NSNotFound && pmRange.location == NSNotFound);

Wednesday 9 April 2014

UIKeyboard notifications Show & Hide - iPhone SDK

This post will help you integrate keyboard     Notifications to handle the show and hide functionality 

Below are two observer which keep listening keyboard actions . You can keep this two observer in viewdidload
OBSERVERS:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardDidShowNotification object:nil];

   

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardDidHideNotification object:nil];


These are two delegate methods and these will be trigered on keyboard actions.

DELEGATE METHODS:
- (void)keyboardWillShow:(NSNotification*)notification
{
    
}
-(void)keyboardWillHide: (NSNotification*)notification
{
    

}

Tuesday 8 April 2014

Check Email validation

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

}

ASIFormDataRequest UPLOAD IMAGE TO THE SERVER

NSMutableDictionary *dic=[NSMutableDictionary dictionary];
        
        [dic setValue:@"Abdul Kareem" forKeyPath:@"user_name"];
        [dic setValue:@"signup" forKeyPath:@"action"];        
        [dic setValue:@"a.kareem.tn@gmail.com" forKeyPath:@"email"];
        [dic setValue:@"abc" forKeyPath:@"password"];
        [dic setValue:@"28" forKeyPath:@"age"];
        [dic setValue:@"Male" forKeyPath:@"gender"];
        [dic setValue:@"80" forKeyPath:@"weight"];
        [dic setValue:@"6" forKeyPath:@"height"];

        NSString *jsonRequest = [dic JSONRepresentation];
        jsonRequest =[jsonRequest stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

        NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@",SERVIEC_URL,jsonRequest]];

        ASIFormDataRequest *request =[ASIFormDataRequest requestWithURL:url];

        [request setRequestMethod:@"POST"];
        
        [request addRequestHeader:@"User-Agent" value:@"ASIHTTPRequest"];
        [request addRequestHeader:@"Content-Type" value:@"application/json"];
        //[request appendPostData:[jsonRequest  dataUsingEncoding:NSUTF8StringEncoding]];

        if (imageData != nil) { ///for image data
            [request setData:imageData withFileName:@"image.jpg" andContentType:@"image/jpeg" forKey:@"picture"];
        }
       
        [request setDelegate:self];
        [request setShowAccurateProgress:YES];
        
        [request setUsername:"user name if you have on webservice"];
        [request setPassword:"password if you have on webservice"];

        [request startAsynchronous];

Thursday 27 March 2014

SIMPLE PROTOCOL & DELEGATE EXAMPLE

PROTOCOL & DELEGATE
two controllers

FirstViewController
SecondViewController

SecondViewController.h
@protocol SecondViewControllerDelegate;
@property (nonatomic, weak) id<SecondViewControllerDelegate> delegate;

@protocol SecondViewControllerDelegate <NSObject>

- (void)SecondViewController:(SecondViewController*)viewController
             didChooseValue:(CGFloat)value;

SecondViewController.m
-(IBAction)SecondTap:(id)sender
{
    id<SecondViewControllerDelegate> strongDelegate = self.delegate;
    
    // Our delegate method is optional, so we should
    // check that the delegate implements it
    
    if ([strongDelegate respondsToSelector:@selector(SecondViewController:didChooseValue:)]) {
        [strongDelegate SecondViewController:self didChooseValue:[sender tag]];
    }
}

FirstViewController.h

@interface FirstViewController : UIViewController<SecondViewControllerDelegate>

FirstViewController.m

-(IBAction)Add:(id)sender
{
    SecondViewController *objsecond =[[SecondViewController alloc]init];
    [objsecond setDelegate:self];
    [self.view addSubview:objsecond.view];

}

- (void)SecondViewController:(SecondViewController *)viewController didChooseValue:(CGFloat)value
{
    
    // Do something with value...
    
    // ...then dismiss the child view controller
    [viewController.view removeFromSuperview];

}

Tuesday 18 March 2014

Generate PEM certificate from P12 certificate

Open terminal and go to the path where you place p12 certificate and run this complete below command:

openssl pkcs12 -in certificateName.p12 -out certificateName.pem -nodes

iOS Timer Counter !!


Here is the Timer counter simple example in which we will get seconds, minutes, and hours

Call the below method TimerCounter:

int secondsSpent;
NSTimer *timer= [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(TimeCounter) userInfo:nil repeats:YES];

- (void)TimeCounter
{
    secondsSpent ++ ;
    hours = secondsSpent / 3600;
    minutes = (secondsSpent % 3600) / 60;
    seconds = (secondsSpent %3600) % 60;
    NSLog(@"Time spent: %02d:%02d:%02d", hours, minutes, seconds);

}

iOS Local Notifications

Here we have sample code for local notification

    UILocalNotification *notification = [[UILocalNotification alloc] init];
    notification.alertBody =@"Test Message";
    notification.soundName = UILocalNotificationDefaultSoundName;
    

    [[UIApplication sharedApplication] presentLocalNotificationNow:notification];

How null,nill, and lenght 0 object can be checked ???

The simplest way to check NSNull value , nill value, and lenght =0 of object:

static inline BOOL IsEmpty(id object)
{
    return object == nil
    || ([object respondsToSelector:@selector(length)]
        && [(NSData *) object length] == 0)
    || ([object respondsToSelector:@selector(count)]
        && [(NSArray *) object count] == 0)
    || ([object respondsToSelector:@selector(count)]
        && object == nil)
    || ([object respondsToSelector:@selector(count)]
        && [ object isKindOfClass:[NSNull class]]);
    

}


How to call inline function:

 NSString *str =nil;
    
    if(!(IsEmpty(str)))
    {
        NSLog(@"The object is not null, nill,");

    }