Powered By Blogger

Friday, May 27, 2011

how to fetch contacts from iPhone using programmatically?

 Hi everyone,
This will help you to fetch contact information from your iOS Device Address book. First you have to include "AddressBookUI.framework" into your project and then you have to include "UINavigationControllerDelegate","ABPeoplePickerNavigationControllerDelegate" into header part of the controller. You have to also import "#import <AddressBookUI/AddressBookUI.h>" into current controller's header part.

#pragma mark -
#pragma mark Button Action Event

-(IBAction)callAddressbook:(id)sender
{
            ABPeoplePickerNavigationController *addressBookController = [[ABPeoplePickerNavigationController alloc]init];
            addressBookController.peoplePickerDelegate = self;
            addressBookController.delegate = self;
            addressBookController.navigationBar.tintColor = [UIColor blackColor];
            addressBookController.searchDisplayController.searchBar.tintColor = [UIColor blackColor];
            addressBookController.searchDisplayController.searchBar.backgroundColor = [UIColor blackColor];
            [self presentModalViewController:addressBookController animated:YES];
            [addressBookController release];
            addressBookController = nil;
}

#pragma mark -
#pragma mark ABPeoplePickerNavigationController Delegate Method


- (void)peoplePickerNavigationControllerDidCancel:(ABPeoplePickerNavigationController *)peoplePicker // called when address book closed
{
    [peoplePicker dismissModalViewControllerAnimated:YES];
}

- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker  // called when select any contact from address book
      shouldContinueAfterSelectingPerson:(ABRecordRef)person
{
  
    ABMultiValueRef addresses = [(NSMutableDictionary *)ABRecordCopyValue(person, kABPersonAddressProperty) autorelease];
    NSArray *addressesArray = [(NSArray *)ABMultiValueCopyArrayOfAllValues(addresses) autorelease];
    NSDictionary *dictAddress = [addressesArray objectAtIndex:0];
  
    ABMultiValueRef phone = [(NSMutableDictionary *)ABRecordCopyValue(person, kABPersonPhoneProperty) autorelease];
    NSArray *phoneArray = [(NSArray *)ABMultiValueCopyArrayOfAllValues(phone) autorelease];
    NSMutableString *strPhone = [NSMutableString string];
  
    for (int i=0; i<[phoneArray count]; i++)
    {
        [strPhone appendString:[NSString stringWithFormat:@"%@,",[phoneArray objectAtIndex:i]]];
    }
  
    [ApplicationData sharedInstance].selectedContact.contactId = (NSInteger) ABRecordGetRecordID(person);
    [ApplicationData sharedInstance].selectedContact.firstName = [(NSString *)ABRecordCopyValue(person, kABPersonFirstNameProperty) autorelease]==nil?@"":[(NSString *)ABRecordCopyValue(person, kABPersonFirstNameProperty)autorelease];
    [ApplicationData sharedInstance].selectedContact.lastName = [(NSString *)ABRecordCopyValue(person, kABPersonLastNameProperty)autorelease]==nil?@"":[(NSString *)ABRecordCopyValue(person, kABPersonLastNameProperty)autorelease];
    [ApplicationData sharedInstance].selectedContact.street = [dictAddress valueForKey:@"Street"]==nil?@"":[dictAddress valueForKey:@"Street"];
    [ApplicationData sharedInstance].selectedContact.telephone =  [strPhone stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@","]];
    [ApplicationData sharedInstance].selectedContact.city = [dictAddress valueForKey:@"City"]==nil?@"":[dictAddress valueForKey:@"City"];
    [ApplicationData sharedInstance].selectedContact.postcode = [dictAddress valueForKey:@"ZIP"]==nil?@"":[dictAddress valueForKey:@"ZIP"];
    [ApplicationData sharedInstance].selectedContact.state = [dictAddress valueForKey:@"State"]==nil?@"":[dictAddress valueForKey:@"State"];
    [ApplicationData sharedInstance].selectedContact.country = [dictAddress valueForKey:@"CountryCode"]==nil?@"":[dictAddress valueForKey:@"CountryCode"];
  
  
    [ApplicationData sharedInstance].obj_sendOrder.recipientName = [NSString stringWithFormat:@"%@ %@",[ApplicationData sharedInstance].selectedContact.firstName,[ApplicationData sharedInstance].selectedContact.lastName];
    [ApplicationData sharedInstance].obj_sendOrder.street = [ApplicationData sharedInstance].selectedContact.street;
    [ApplicationData sharedInstance].obj_sendOrder.city = [ApplicationData sharedInstance].selectedContact.city;
    [ApplicationData sharedInstance].obj_sendOrder.zip = [ApplicationData sharedInstance].selectedContact.postcode;
    [ApplicationData sharedInstance].obj_sendOrder.state = [ApplicationData sharedInstance].selectedContact.state;
    [ApplicationData sharedInstance].obj_sendOrder.country = [ApplicationData sharedInstance].selectedContact.country;
  
    [ApplicationData sharedInstance].obj_sendOrder.contactType = @"Phone";
  
    dictAddress = nil;
    addresses = nil;
    addressesArray = nil;
  
    phone = nil;
    phoneArray = nil;
    strPhone = nil;
  
    [peoplePicker dismissModalViewControllerAnimated:YES];
    return NO;
}

- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker
      shouldContinueAfterSelectingPerson:(ABRecordRef)person
                                property:(ABPropertyID)property
                              identifier:(ABMultiValueIdentifier)identifier // called to show detail of contact
{
    return NO;
}
Still if you have questions regarding this then you can ask me anytime.

Thanks & Regards,
Nilesh Prajapati

Saturday, May 21, 2011

AirPrint in iPhone SDK

Hi Everyone,
By using below code , you'll be able to print your view using AirPrint in iPhone SDK.

-(void)sendToPrinter
{

    NSString *filename = [appDelegate.pdfFilePath lastPathComponent];   
    filename = [filename stringByReplacingOccurrencesOfString:@".pdf" withString:@""];
    NSString *path = [[NSBundle mainBundle] pathForResource:filename ofType:@"pdf"];

    NSData *myData = [NSData dataWithContentsOfFile:path];
    UIPrintInteractionController *print = [UIPrintInteractionController sharedPrintController];

    print.delegate = self;
    UIPrintInfo *printInfo = [UIPrintInfo printInfo];
    printInfo.outputType = UIPrintInfoOutputGeneral;
    printInfo.jobName = [appDelegate.pdfFilePath lastPathComponent];
    printInfo.duplex = UIPrintInfoDuplexLongEdge;
    print.printInfo = printInfo;
    print.showsPageRange = YES;
    print.printingItem = myData;
    UIViewPrintFormatter *viewFormatter = [self.view viewPrintFormatter];
    viewFormatter.startPage = 0;
    print.printFormatter = viewFormatter;
   

    UIPrintInteractionCompletionHandler completionHandler = ^(UIPrintInteractionController *printInteractionController, BOOL completed, NSError *error) {};
   
    [print presentAnimated:YES completionHandler:completionHandler];
}

if you have query then send it to me. 

Thanks and Regards,
 Nilesh Prajapati

Thursday, April 7, 2011

Custom Alert View (UIAlertView)

  ************************** Starting Of Header File Part ***************************


 #import <UIKit/UIKit.h>
#define OVALSCALEX 1.0
#define OVALSCALEY 70.0/425.0

@interface CustomAleartView : UIAlertView <UIAlertViewDelegate> {

}
- (void) drawRoundedRect:(CGRect) rect
          withBackground:(UIColor *) backgroundColor
               andBorder:(UIColor *) borderColor
               andRadius:(CGFloat) radius
              andContext:(CGContextRef)cntxt;

@end

 ************************** Starting Of Implementation Part ***************************

#import "CustomAleartView.h"


@implementation CustomAleartView


- (id)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        // Initialization code
    }
    return self;
}
- (void)willPresentAlertView:(UIAlertView *)alertView{
   
    self.frame = CGRectMake(10, 20, 420, 300);
}

- (void)drawRect:(CGRect)rect {
    // Drawing code
    CGContextRef context = UIGraphicsGetCurrentContext ();
    [self drawRoundedRect:rect withBackground:[UIColor blackColor] andBorder:[UIColor whiteColor] andRadius:10.0  andContext:context];
}

- (void) drawRoundedRect:(CGRect) rect
          withBackground:(UIColor *) backgroundColor
               andBorder:(UIColor *) borderColor
               andRadius:(CGFloat) radius
              andContext:(CGContextRef)cntxt
{
    CGContextRef context = cntxt;
   
    CGContextSaveGState (context);
   
    //Calculate rounded form
    CGMutablePathRef     roundedPath = CGPathCreateMutable ();
   
    CGPathMoveToPoint (roundedPath, NULL, CGRectGetMinX (rect) + radius, CGRectGetMinY (rect));
    CGPathAddArc (roundedPath, NULL, CGRectGetMaxX (rect)-radius, CGRectGetMinY (rect)+radius, radius, 3*M_PI/2, 0, 0);
    CGPathAddArc (roundedPath, NULL, CGRectGetMaxX (rect)-radius, CGRectGetMaxY (rect)-radius, radius, 0, M_PI/2, 0);
    CGPathAddArc (roundedPath, NULL, CGRectGetMinX (rect)+radius, CGRectGetMaxY (rect)-radius, radius, M_PI/2, M_PI, 0);
    CGPathAddArc (roundedPath, NULL, CGRectGetMinX (rect)+radius, CGRectGetMinY (rect)+radius, radius, M_PI, 3*M_PI/2, 0);    
    CGPathCloseSubpath (roundedPath);
   
   
   
    //If background defined, fill roundedPath and add some light effect from the top
   
    if (backgroundColor)
    {
        //Fill background
        CGContextSetFillColorWithColor (context, [backgroundColor CGColor]);
        CGContextAddPath (context, roundedPath);
        CGContextFillPath (context);
       
        //Clip area
        CGContextAddPath (context, roundedPath);         
        CGContextClip (context);
       
       
        //     Draw elipse
        CGContextSetFillColorWithColor (context, [[[UIColor whiteColor] colorWithAlphaComponent:40.0/255.0] CGColor]);
       
       
       
        CGContextScaleCTM (context, OVALSCALEX, OVALSCALEY);
        CGContextAddArc (context,
                         (rect.origin.x+rect.size.width/2.0)/OVALSCALEX,
                         (rect.origin.y+0.0)/OVALSCALEY,
                         rect.size.width/2.0*425.0/270.0,
                         0.0, 2*M_PI, 1);
        CGContextFillPath (context);
       
        CGContextRestoreGState (context);     // Reset CTM
        CGContextSaveGState (context);         
    }
   
    if (borderColor)
    {
        CGContextSetStrokeColorWithColor (context, [borderColor CGColor]);
        CGContextSetLineWidth (context, 3.0);
        CGContextAddPath (context, roundedPath);
        CGContextStrokePath (context);
    }
   
    CFRelease (roundedPath);
   
    CGContextRestoreGState (context);
}


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

@end

UIKeyborad Notification

Hi friends,
This informs you how to use UIKeyboardNotification into your project. By using this , you can make your custom animation at the time of keyboard appears/disappears.

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
   
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                               name:UIKeyboardWillShowNotification
                                               object:nil];
   
    [[NSNotificationCenter defaultCenter] removeObserver:self

                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
}

- (void)keyboardShow:(NSNotification *)aNotification
{
    // the keyboard is showing so resize the table's height
    CGRect keyboardRect = [[[aNotification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    NSTimeInterval animationDuration =
        [[[aNotification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    CGRect frame = self.view.frame;
    frame.size.height -= keyboardRect.size.height;
    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
    [UIView setAnimationDuration:animationDuration];
    self.view.frame = frame;
    [UIView commitAnimations];
}

- (void)keyboardHide:(NSNotification *)aNotification
{
    // the keyboard is hiding reset the table's height
    CGRect keyboardRect = [[[aNotification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    NSTimeInterval animationDuration =
        [[[aNotification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    CGRect frame = self.view.frame;
    frame.size.height += keyboardRect.size.height;
    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
    [UIView setAnimationDuration:animationDuration];
    self.view.frame = frame;
    [UIView commitAnimations];
}

If any one has query then place you it over here.

Thanks and Regards,
Nilesh Prajapati
 

UIViewAnimation Transition Code

    UIView *kView;

    CGContextRef context = UIGraphicsGetCurrentContext();
    [UIView beginAnimations:@"Right Flip" context:context];
    [UIView setAnimationTransition: UIViewAnimationTransitionFlipFromRight forView:kView cache:YES];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
    [UIView setAnimationDuration:0.3];
    [UIView setAnimationDelegate:self];
    [UIView commitAnimations];

Saturday, February 5, 2011

Image with Rounded Curve


static void addRoundedRectToPath(CGContextRef context, CGRect rect, float ovalWidth, float ovalHeight)
{
    float fw, fh;
    if (ovalWidth == 0 || ovalHeight == 0) {
        CGContextAddRect(context, rect);
        return;
    }
    CGContextSaveGState(context);
    CGContextTranslateCTM (context, CGRectGetMinX(rect), CGRectGetMinY(rect));
    CGContextScaleCTM (context, ovalWidth, ovalHeight);
    fw = CGRectGetWidth (rect) / ovalWidth;
    fh = CGRectGetHeight (rect) / ovalHeight;
    CGContextMoveToPoint(context, fw, fh/2);
    CGContextAddArcToPoint(context, fw, fh, fw/2, fh, 1);
    CGContextAddArcToPoint(context, 0, fh, 0, fh/2, 1);
    CGContextAddArcToPoint(context, 0, 0, fw/2, 0, 1);
    CGContextAddArcToPoint(context, fw, 0, fw, fh/2, 1);
    CGContextClosePath(context);
    CGContextRestoreGState(context);
}

-(UIImage *)getRoundCornerOfImage:(UIImage *)image
{
    int w = image.size.width;
    int h = image.size.height;
   
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef context = CGBitmapContextCreate(NULL, w, h, 8, 4 * w, colorSpace, kCGImageAlphaPremultipliedFirst);
   
    CGContextBeginPath(context);
    CGRect rect = CGRectMake(0, 0, image.size.width, image.size.height);
    addRoundedRectToPath(context, rect, 10, 10);
    CGContextClosePath(context);
    CGContextClip(context);
   
    CGContextDrawImage(context, CGRectMake(0, 0, w, h), image.CGImage);
   
    CGImageRef imageMasked = CGBitmapContextCreateImage(context);
    CGContextRelease(context);
    CGColorSpaceRelease(colorSpace);
    return [UIImage imageWithCGImage:imageMasked];
}

And Then just use like :
UIImage *Roundimage = [self getRoundCornerOfImage:originalImage];

Thursday, January 20, 2011

UIImagePickerControler

 #pragma mark -
#pragma mark Camera Open Method

-(void)cameraCalling {
    UIImagePickerController *picker;

    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
    {  
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        picker.cameraOverlayView = lblEvent;
        [picker setShowsCameraControls:YES];
    }
    else
    {
        picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    }
    picker.allowsImageEditing =YES;
  
    [self presentModalViewController:picker animated:TRUE];
  
}



#pragma mark -
#pragma mark imagePickerController Methods

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo;
{
    if (!error)
        NSLog(@"Image written to photo album");
    else
        NSLog(@"Error writing to photo album: %@", [error localizedDescription]);


}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo
{
    count ++;
    isRemoved = NO;
    capturedImg = image;
    imgView.image = image;
   
    NSData *imageData = UIImageJPEGRepresentation(image, 1.1);
    NSString *base64String=@"";
    if(imageData)
    {
        base64String=[imageData base64Encoding];
    }
   
    NSDate *date = [NSDate date];
    NSDateFormatter *df = [[NSDateFormatter alloc]init];
    [df setDateFormat:@"MM-dd-yyyy"];
    NSString *str1= [df stringFromDate:date];
    [df setTimeStyle:NSDateFormatterShortStyle];
    NSString *str2= [df stringFromDate:date];
   
    NSLog(@"%@ %@",str1,str2);
    appDelegate.fileName =[NSString stringWithFormat:@"%@ %@",str1,str2];
    [self saveImage:image :appDelegate.fileName];

   
    //UIImageWriteToSavedPhotosAlbum(image, picker, @selector(image:didFinishSavingWithError:contextInfo:), nil);
}
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [self dismissModalViewControllerAnimated:YES];

}