Wednesday, 30 July 2014

Add Multiple Images to ScrollView with PageControll

This is the code that I use when setting up a UIScrollView to contain multiple images that can be scrolled through. It has PageControl which shows no. of image as well.

Call this method from your Desired method (viewDidLoad or  viewWillAppear)


-(void) setupScrollView
 {
    //add the scrollview to the view

    self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0,
                                                                     self.view.frame.size.width,
                                                                     self.view.frame.size.height)];
    self.scrollView.pagingEnabled = YES;

    [self.scrollView setAlwaysBounceVertical:NO];

    //setup internal views
    NSInteger numberOfViews = 3;

    for (int i = 0; i < numberOfViews; i++) 
{
        CGFloat xOrigin = i * self.view.frame.size.width;

        // add PageControl

        self.pageControl = [[UIPageControl alloc] init];

        self.pageControl.frame = CGRectMake(xOrigin+120, 175, 90, 37);

        self.pageControl.numberOfPages = 5;

        self.pageControl.pageIndicatorTintColor = [UIColor blackColor];

        self.pageControl.currentPageIndicatorTintColor = [UIColor greenColor];

        self.pageControl.currentPage = i;

        UIImageView *image = [[UIImageView alloc] initWithFrame:
                              CGRectMake(xOrigin, 0,
                                         self.view.frame.size.width,
                                         self.view.frame.size.height)];

       image.image = [UIImage imageNamed:[NSString stringWithFormat:@"%@",[imgArray objectAtIndex:i]]];      // imgArray is Array of Images

        image.contentMode = UIViewContentModeScaleToFill;

        [self.scrollView addSubview:image];
 }
    //set the scroll view content size
    self.scrollView.contentSize = CGSizeMake(self.view.frame.size.width *
                                             numberOfViews,
                                             self.view.frame.size.height);

    //add the scrollview to this view
    [self.view addSubview:self.scrollView];

}


Thnx & Regards
Mohit Popat

Tuesday, 6 May 2014

Send Email form iOS Application


To Send Email from iOS Application you must have to import MessageUI Framework to your application.

To add this Framework Select -> Target -> Build Phases -> Link Binary with Libraries


Next, click "+" button and select "MessageUI Framework" and click the Add button. After you click the Add button Framework will be added to your application. 



Now import Framework in your file.

#import <MessageUI/MessageUI.h>

Add MFMailComposeDelegate 
@interface ViewController : UIViewController<MFMailComposeViewControllerDelegate

Now write below code to send mail from our app. here I have added one button named "Send Email"and connected my below method to it to send the mail. You can put this code from where ever you wants to send mail.

- (IBAction)sendEmail:(id)sender
{
    // Email Subject
    NSString *emailTitle = @"Test mail";
    // Email Content
    NSString *messageBody = @"It is Mail for testing!";
    // To address
    NSArray *toRecipents = [NSArray arrayWithObject:@"ios@gmail.com"];
    
    MFMailComposeViewController *mc = [[MFMailComposeViewController alloc] init];
    mc.mailComposeDelegate = self;
    [mc setSubject:emailTitle];
    [mc setMessageBody:messageBody isHTML:NO];
    [mc setToRecipients:toRecipents];
    
    // Present mail view controller on screen
    [self presentViewController:mc animated:YES completion:NULL];
    
}

This is Delegate method of MFMailComposeViewController. This method will be called automatically when the mail interface is closed. (e.g. user cancel the operation or mail sent)

- (void) mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error
{
    switch (result)
    {
        case MFMailComposeResultCancelled:
            NSLog(@"Mail cancelled");
            break;
        case MFMailComposeResultSaved:
            NSLog(@"Mail saved");
            break;
        case MFMailComposeResultSent:
            NSLog(@"Mail sent");
            break;
        case MFMailComposeResultFailed:
            NSLog(@"Mail sent failure: %@", [error localizedDescription]);
            break;
        default:
            break;
    }
    
    // Close the Mail Interface
    [self dismissViewControllerAnimated:YES completion:NULL];
}

Build and Run and you will see just like that


Compose HTML mail if you wants. then you just have to make only one change. set isHTML to YES message body

[mc setMessageBody:messageBody isHTML:YES];

And write HTML Tags to your body just like that.


NSString *messageBody = @"<h1>Learning iOS Programming!</h1>";


Thanks & Regards
Mohit Popat

                                                                                                                                                                  

Tuesday, 29 April 2014

Disable ARC for Single file in Project

it is possible to Disable ARC for individual files by adding the  -fno-objc-arc  compiler flags for those files.

To add Compiler flags go to Targets -> Build Phases -> Compile Sources. you have to double click on right column of the row under Compiler Flags. you can also add it to multiple files by holding the cmd button to select the files and then pressing enter to bring up the flag edit box.







Thanks & Regards
Mohit Popat
                                                                                                                                                                            

Wednesday, 23 April 2014

Save and Retrieve data from NSUserDefaults

 NSUserDefaults *userDefaults=[NSUserDefaults standardUserDefaults];  

Set values to userDefaults 
 [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"];  

 [userDefaults synchronize];  

Thats all. all your values will be stored in your userDefaults.
Get Values from userDefaults.


 NSUserDefaults *userDefaults=[NSUserDefaults standardUserDefaults];  

 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"];  

Wednesday, 16 April 2014

Add UIPanGestureRecognizer to View

Adding PanGestureRecognizer to your view its very easy.

Here i have added PanGestureRecognizer to ImageView. so i can move my imageview in my view.

Add following code to any method to add PanGestureRecognizer to your view. i added this to ViewWillAppear.


-(void)viewWillAppear:(BOOL)animated
{
         UIPanGestureRecognizer *panRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePan:)];

          [panRecognizer setMinimumNumberOfTouches:1];

          [panRecognizer setMaximumNumberOfTouches:1];

          [ViewMain addGestureRecognizer:panRecognizer];

          [panRecognizer release];
}
- (Void)handlePan:(UIPanGestureRecognizer *)recognizer
    {
   
         CGPoint translation = [recognizer translationInView:self.view];
         recognizer.view.center = CGPointMake(recognizer.view.center.x + translation.x,
                                         recognizer.view.center.y + translation.y);
         [recognizer setTranslation:CGPointMake(0, 0) inView:self.view];
     
         if (recognizer.state == UIGestureRecognizerStateEnded) {
       
             CGPoint velocity = [recognizer velocityInView:self.view];
             CGFloat magnitude = sqrtf((velocity.x * velocity.x) + (velocity.y * velocity.y));
            CGFloat slideMult = magnitude / 200;
            NSLog(@"magnitude: %f, slideMult: %f", magnitude, slideMult);
       
            float slideFactor = 0.1 * slideMult; // Increase for more of a slide
            CGPoint finalPoint = CGPointMake(recognizer.view.center.x + (velocity.x * slideFactor),
                                         recognizer.view.center.y + (velocity.y * slideFactor));
        finalPoint.x = MIN(MAX(finalPoint.x, 0), self.view.bounds.size.width);
        finalPoint.y = MIN(MAX(finalPoint.y, 0), self.view.bounds.size.height);
       
        [UIView animateWithDuration:slideFactor*2 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
            recognizer.view.center = finalPoint;
        } completion:nil];
       
    }
   
    }
That's it


Thanks & Regards
Mohit Popat

Saturday, 12 April 2014

Add UI Controls Programmatically

It is very easy to Add Controls programmatically we just need to set the frames of controls as per our requirements.

In this post i have added UIView, UIImageView, UILabel, UIButton and UITextField.

- (void)viewDidLoad
{
        [super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
    
    UIView *dynamicView=[[UIView alloc]initWithFrame:CGRectMake(10, 15, 300, 500)];
    [dynamicView setBackgroundColor:[UIColor grayColor]];
    [self.view addSubview:dynamicView];
    
    UIImageView *imageView=[[UIImageView alloc]initWithFrame:CGRectMake(0, 20, 140, 150)];
    [imageView setImage:[UIImage imageNamed:@"audi.png"]];
    [dynamicView addSubview:imageView];
    
    UIImageView *imageView2=[[UIImageView alloc]initWithFrame:CGRectMake(160, 20, 140, 150)];
    [imageView2 setImage:[UIImage imageNamed:@"bmw.png"]];
    [dynamicView addSubview:imageView2];
    
    UILabel *label1=[[UILabel alloc]initWithFrame:CGRectMake(60, 180, 50, 20)];
    [label1 setBackgroundColor:[UIColor clearColor]];
    [label1 setText:@"Audi"];
    [label1 setTextAlignment:UITextAlignmentCenter];
    [label1 setFont:[UIFont systemFontOfSize:20.0f]];
    [dynamicView addSubview:label1];
    
    UILabel *label2=[[UILabel alloc]initWithFrame:CGRectMake(200, 180, 50, 20)];
    [label2 setBackgroundColor:[UIColor clearColor]];
    [label2 setText:@"BMW"];
    [label2 setTextAlignment:UITextAlignmentCenter];
    [label2 setFont:[UIFont systemFontOfSize:20.0f]];
    [dynamicView addSubview:label2];
    
    
    UITextField *textfield=[[UITextField alloc]initWithFrame:CGRectMake(10, 250, 120, 30)];
    [textfield setBorderStyle:UITextBorderStyleRoundedRect];
    [textfield setText:@"Demo Text"];
    [dynamicView addSubview:textfield];
    
    UIButton *dynamicButton=[UIButton buttonWithType:UIButtonTypeRoundedRect];
    [dynamicButton setFrame:CGRectMake(200, 250, 80, 30)];
    [dynamicButton setTitle:@"Click Me" forState:UIControlStateNormal];
    [dynamicButton addTarget:self action:@selector(buttonClicked) forControlEvents:UIControlEventTouchUpInside];
    [dynamicView addSubview:dynamicButton];


}

// Method for button 

-(IBAction)buttonClicked;
{
    NSLog(@"Button Clicke Event Called");
}

Build and Run and you will get Output like this 


Thanks & Regards
Mohit Popat

Friday, 11 April 2014

Import Contacts from Device to Application

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. 


#import <AddressBookUI/AddressBookUI.h>

@interface ViewController :  UIViewController<UINavigationControllerDelegate,ABPeoplePickerNavigationControllerDelegate>

Declare one method to pick up contacts


-(IBAction)callAddressbook:(id)sender;

Make Connection of this method with your button.

Declare two objects in your interface section. one Array object to store the contact information.

@property (nonatomic, strong) NSMutableArray *arrContactsData;
@property (nonatomic, strong) ABPeoplePickerNavigationController *addressBookController;

Now put the following code in your button's event. it will open your contacts list

-(IBAction)callAddressbook:(id)sender
{
    _addressBookController = [[ABPeoplePickerNavigationController alloc] init];
    [_addressBookController setPeoplePickerDelegate:self];
    [self presentViewController:_addressBookController animated:YES completion:nil];

}

Now we will call Delagate methods of ABPeoplePickerNavigationController

#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
{
    
    // Initialize a mutable dictionary and give it initial values.
    NSMutableDictionary *contactInfoDict = [[NSMutableDictionary alloc]
                                            initWithObjects:@[@"", @"", @"", @"", @"", @"", @"", @"", @"",@""]
                                            forKeys:@[@"firstName", @"lastName", @"mobileNumber", @"homeNumber", @"homeEmail", @"workEmail", @"address", @"zipCode", @"city",@"birthDate"]];
    
    // Use a general Core Foundation object.
    CFTypeRef generalCFObject = ABRecordCopyValue(person, kABPersonFirstNameProperty);
    
    // Get the first name.
    if (generalCFObject)
 {
        [contactInfoDict setObject:(__bridge NSString *)generalCFObject forKey:@"firstName"];
        CFRelease(generalCFObject);
 }
    
    // Get the last name.
    generalCFObject = ABRecordCopyValue(person, kABPersonLastNameProperty);

    if (generalCFObject) {
        [contactInfoDict setObject:(__bridge NSString *)generalCFObject forKey:@"lastName"];
        CFRelease(generalCFObject);
    }
    
    // Get the phone numbers as a multi-value property.

    ABMultiValueRef phonesRef = ABRecordCopyValue(person, kABPersonPhoneProperty);

    for (int i=0; i<ABMultiValueGetCount(phonesRef); i++)
 {
        CFStringRef currentPhoneLabel = ABMultiValueCopyLabelAtIndex(phonesRef, i);
        CFStringRef currentPhoneValue = ABMultiValueCopyValueAtIndex(phonesRef, i);
        
        if (CFStringCompare(currentPhoneLabel, kABPersonPhoneMobileLabel, 0) == kCFCompareEqualTo)
    {
            [contactInfoDict setObject:(__bridge NSString *)currentPhoneValue forKey:@"mobileNumber"];
    }
        
    if (CFStringCompare(currentPhoneLabel, kABHomeLabel, 0) == kCFCompareEqualTo)
   {
            [contactInfoDict setObject:(__bridge NSString *)currentPhoneValue forKey:@"homeNumber"]
   }
        
        CFRelease(currentPhoneLabel);
        CFRelease(currentPhoneValue);
    }
    CFRelease(phonesRef);
    
    
    // Get the e-mail addresses as a multi-value property.

    ABMultiValueRef emailsRef = ABRecordCopyValue(person, kABPersonEmailProperty);

    for (int i=0; i<ABMultiValueGetCount(emailsRef); i++)
  {
        CFStringRef currentEmailLabel = ABMultiValueCopyLabelAtIndex(emailsRef, i);
        CFStringRef currentEmailValue = ABMultiValueCopyValueAtIndex(emailsRef, i);
        
        if (CFStringCompare(currentEmailLabel, kABHomeLabel, 0) == kCFCompareEqualTo)
       {
            [contactInfoDict setObject:(__bridge NSString *)currentEmailValue forKey:@"homeEmail"];
        }
        
        if (CFStringCompare(currentEmailLabel, kABWorkLabel, 0) == kCFCompareEqualTo)
      {
            [contactInfoDict setObject:(__bridge NSString *)currentEmailValue forKey:@"workEmail"];
      }
        
        CFRelease(currentEmailLabel);
        CFRelease(currentEmailValue);
    }
    CFRelease(emailsRef);
    
    
    // Use a general Core Foundation object for fetching Birth Date.

    CFTypeRef generalObject = ABRecordCopyValue(person, kABPersonBirthdayProperty);
    
    if (generalCFObject)
    {
        [contactInfoDict setObject:(__bridge NSString *)generalObject forKey:@"birthDate"];
        CFRelease(generalCFObject);
    }
    
    // Get the first street address among all addresses of the selected contact.

    ABMultiValueRef addressRef = ABRecordCopyValue(person, kABPersonAddressProperty);

    if (ABMultiValueGetCount(addressRef) > 0)
  {
        NSDictionary *addressDict = (__bridge NSDictionary *)ABMultiValueCopyValueAtIndex(addressRef, 0);
        
        [contactInfoDict setObject:[addressDict objectForKey:(NSString *)kABPersonAddressStreetKey] forKey:@"address"];
        [contactInfoDict setObject:[addressDict objectForKey:(NSString *)kABPersonAddressZIPKey] forKey:@"zipCode"];
        [contactInfoDict setObject:[addressDict objectForKey:(NSString *)kABPersonAddressCityKey] forKey:@"city"];
    }
    CFRelease(addressRef);
    
    
    // If the contact has an image then get it too.

    if (ABPersonHasImageData(person))
   {
        NSData *contactImageData = (__bridge NSData *)ABPersonCopyImageDataWithFormat(person, kABPersonImageFormatThumbnail);
        
        [contactInfoDict setObject:contactImageData forKey:@"image"];
    }
    
    // Initialize the array if it's not yet initialized.

    if (_arrContactsData == nil) {
        _arrContactsData = [[NSMutableArray alloc] init];
    }
    // Add the dictionary to the array.
    [_arrContactsData addObject:contactInfoDict];
    
    // Reload the table view data.
    //[self.tableView reloadData];
    
    // Dismiss the address book view controller.

    [_addressBookController dismissViewControllerAnimated:YES completion:nil];
    
    NSLog(@"Contact details is : %@",contactInfoDict);
    
    return NO;
}

- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker
      shouldContinueAfterSelectingPerson:(ABRecordRef)person
                                property:(ABPropertyID)property
                              identifier:(ABMultiValueIdentifier)identifier // called to show detail of contact
{
    return NO;
}

Finished now build Run your code now and click on your button your contacts list will be open


Click on any contact and all details of that contact will be store in contactInfoDict,

Thanks & Regards 
Mohit Popat