Search This Blog

Thursday 6 December 2012

Fetch Contacts in iOS 6.0 and Lower versions iPhone,iOS

Hi All,

Here I will show you how iOS 6.0 and its lower version differs in AddressBookRef to fetch the contacts.I am going to explain you with the code.Following is the explanation,
This code works on iOS 6.0 as well as on lower versions to fetch the contacts.

We need to declare the macro which stores the iOS version of connected device.
Following macros does this,


#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)

after declaring macros whenever you want to fetch the contacts,just write below code,
-(void) didLoad {

// It compares whether current iOS version is than 6.0  
  if (SYSTEM_VERSION_LESS_THAN(@"6.0")) {
        NSLog(@"<6.0");
       
        //Code to fetch Contacts from lower version of iOS

        ABAddressBookRef UsersAddressBook = ABAddressBookCreate();
        
        
        
        //contains details for all the contacts
        CFArrayRef ContactInfoArray = ABAddressBookCopyArrayOfAllPeople(UsersAddressBook);
        
        //get the total number of count of the users contact
        CFIndex numberofPeople = CFArrayGetCount(ContactInfoArray);
        
        //iterate through each record and add the value in the array
        for (int i =0; i<numberofPeople; i++) {
            ABRecordRef ref = CFArrayGetValueAtIndex(ContactInfoArray, i);
            ABMultiValueRef names = (NSString*)ABRecordCopyValue(ref, kABPersonFirstNameProperty);
            ABMultiValueRef lastname=(NSString*)ABRecordCopyValue(ref, kABPersonLastNameProperty);
            
            ABMultiValueRef emailMultiValue = ABRecordCopyValue(ref, kABPersonEmailProperty);
            NSArray *emailAddresses = [(NSArray *)ABMultiValueCopyArrayOfAllValues(emailMultiValue) autorelease];
            
            
            ABMultiValueRef multi = ABRecordCopyValue(ref, kABPersonPhoneProperty);
            
            NSArray *no2 = [(NSArray*)ABMultiValueCopyArrayOfAllValues(multi) autorelease];
            
            ABMultiValueRef fullName=[NSString stringWithFormat:@"%@ %@",names,lastname];
          
            
            for (int i=0; i<[no2 count]; i++) {
                [arr_name addObject:fullName];
                [arr_ContactsInfo addObject:[no2 objectAtIndex:i]];
            }
            for (int i=0; i<[emailAddresses count]; i++) {
                [arr_name addObject:fullName];
                [arr_ContactsInfo addObject:[emailAddresses objectAtIndex:i]];
            }
            
            
        }

    }else if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"6.0")) {
        NSLog(@">=6.0");

        //When Current iOS >= 6.0 
        ABAddressBookRef addressBookRef = ABAddressBookCreateWithOptions(NULL, NULL);
        
        if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusNotDetermined) {
            ABAddressBookRequestAccessWithCompletion(addressBookRef, ^(bool granted, CFErrorRef error) {
                // First time access has been granted, add the contact
                //contains details for all the contacts
                CFArrayRef ContactInfoArray = ABAddressBookCopyArrayOfAllPeople(addressBookRef);
                
                //get the total number of count of the users contact
                CFIndex numberofPeople = CFArrayGetCount(ContactInfoArray);
                
                //iterate through each record and add the value in the array
                for (int i =0; i<numberofPeople; i++) {
                    ABRecordRef ref = CFArrayGetValueAtIndex(ContactInfoArray, i);
                    ABMultiValueRef names = (NSString*)ABRecordCopyValue(ref, kABPersonFirstNameProperty);
                    ABMultiValueRef lastname=(NSString*)ABRecordCopyValue(ref, kABPersonLastNameProperty);
                    
                    ABMultiValueRef emailMultiValue = ABRecordCopyValue(ref, kABPersonEmailProperty);
                    NSArray *emailAddresses = [(NSArray *)ABMultiValueCopyArrayOfAllValues(emailMultiValue) autorelease];
                    //    CFRelease(emailMultiValue);
                    
                    
                    ABMultiValueRef multi = ABRecordCopyValue(ref, kABPersonPhoneProperty);
                    
                    //  ABMultiValueRef no = (NSString*)ABMultiValueCopyValueAtIndex(multi, 0);
                    NSArray *no2 = [(NSArray*)ABMultiValueCopyArrayOfAllValues(multi) autorelease];
                                       
                    ABMultiValueRef fullName=[NSString stringWithFormat:@"%@ %@",names,lastname];
                    // [arr_name addObject:fullName];
                    //[arr_name addObject:fullName];
                    
                    for (int i=0; i<[no2 count]; i++) {
                        [arr_name addObject:fullName];
                        [arr_ContactsInfo addObject:[no2 objectAtIndex:i]];
                    }
                    for (int i=0; i<[emailAddresses count]; i++) {
                        [arr_name addObject:fullName];
                        [arr_ContactsInfo addObject:[emailAddresses objectAtIndex:i]];
                    }
                    
                    
                    
                }
                
            });
        }
        
     }
     else {
            // The user has previously denied access
            // Send an alert telling user to change privacy setting in settings app
        }


    }

}
If you run the code on iOS < 6.0 it will run as normally and will store the names in arr_name and arr_ContactsInfo array but if you run this code in iOS >= 6.0,it will will ask for the permission from the user whether to allow to fetch contacts.If permission granted,then will store the data in those array.

Happy coding :)

Wednesday 1 August 2012

JSON Post Request iPhone


Here, I am leaving some important notes that you can use in your code for sending data for login page link or a particular forum link using objective C. Also you can use this for posting comments or posting posts to a particular forum or url link.
I am mentioning all the relative apis with the dummy urls for your understanding the whole procedure. Follow the points as per mentioned below

For sake of understanding , take an example of sending username and password to your login page. To do this follow the following steps.

1. set post string with actual username and password.

NSString *post = [NSString stringWithFormat:@"&Username=%@&Password=%@",@"username",@"password"];

2. Encode the post string using NSASCIIStringEncoding and also the post string you need to send in NSData format.

NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

You need to send the actual length of your data. Calculate the length of the post string.

NSString *postLength = [NSString stringWithFormat:@"%d",[postData length]];


3. Create a Urlrequest with all the properties like HTTP method, http header field with length of the post string.
Create URLRequest object and initialize it.

NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];

Set the Url for which your going to send the data to that request.

[request setURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://www.abcde.com/xyz/login.aspx"]]];

Now, set HTTP method (POST or GET).
Write this lines as it is in your code.

[request setHTTPMethod:@"POST"];

Set HTTP header field with length of the post data.

[request setValue:postLength forHTTPHeaderField:@"Content-Length"];

Also set the Encoded value for HTTP header Field.

[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Current-Type"];

Set the HTTPBody of the urlrequest with postData.

[request setHTTPBody:postData];

4. Now, create URLConnection object. Initialize it with the URLRequest.

NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self];

It returns the initialized url connection and begins to load the data for the url request. You can check that whether you URL connection is done properly or not using just if/else statement as below.

if(conn)
{
NSLog(@”Connection Successful”)
}
else
{
NSLog(@”Connection could not be made”);
}

5. To receive the data from the HTTP request , you can use the delegate methods provided by the URLConnection Class Reference. Delegate methods are as below.

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData*)data

Above method is used to receive the data which we get using post method.

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error

This method , you can use to receive the error report in case of connection is not made to server.

- (void)connectionDidFinishLoading:(NSURLConnection *)connection

The above method is used to process the data after connection has made successfully.


Have a Happy Coding !

Monday 2 July 2012

Fetch and Display Data from AddressBook


In this post we will learn on how to retrieve the data from the contact book, and in case you are new to the address book please refer to my earlier post and then continue with this post.
Design Phase: In this demo we shall retrieve some of the values from the address book into our UI, so please prepare a view which looks like something like this

Step 1: Open Xcode and create a windows based application and add the UIViewController subclass file to your project with the name ReteriveSingleData, now this will lead in adding of two new files into your project with the name ReteriveSingleData.h and ReteriveSingleData.m. Make very sure that you have added the AddressBook.framework and the AddressBookUI.framework into your project
Step 2: Please make a view like the one that is shown above and then inside the ReteriveSingleData.h file import the frameworks that you have added
 #import <AddressBookUI/AddressBookUI.h>


Also add a function inside the ReteriveSingleData.h file on the hit of which we will be displaying the address book UI to the user. Its time to code for its body
-(void) getContactData
{
         ABPeoplePickerNavigationController *peoplePicker = [[ABPeoplePickerNavigationController alloc]init];
         peoplePicker.peoplePickerDelegate= self;
         [self presentModalViewController:peoplePicker animated:YES];
         [peoplePicker release];
}
Code Explanation: In the above code I have initialized memory for the people picker controller and set the delegate property to self.
The people picker controller has its delegate method which gets called when a particular value from the people picker is selected and this is the delegate method
-   (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person
here’s the code written inside the body of the delegate method that will help us to pick up the selected value from the address book
-(BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person
{
firstname.text = (NSString*)ABRecordCopyValue(person,kABPersonFirstNameProperty);

lastname.text = (NSString*)ABRecordCopyValue(person,kABPersonLastNameProperty);

//the contact number of a person can be more than one so ABMultiValue is used
 ABMultiValueRef multi = ABRecordCopyValue(person,kABPersonPhoneProperty);
pnumber.text = (NSString*)ABMultiValueCopyValueAtIndex(multi,0);
[self dismissModalViewControllerAnimated:YES]; 
return YES;

}
Code Explanation: The ABRecordCopyValue is a function which accepts two parameter the first parameter is for the record whose value you want to obtain and the second is the property name in record whose value you wish to obtain these two are different things let me give you an example for this
Example: Let’s say inside the database I am a record whose value you want to obtain and so my property name would be name, phone number, address, dob, email etc.
Step 3: Also we have to implement one more delegate method of the ABPeoplePickerController and that delegate method is given below
- (void)peoplePickerNavigationControllerDidCancel:(ABPeoplePickerNavigationController *)peoplePicker;
{
    [self dismissModalViewControllerAnimated:YES];
   
}
we implemented this method because on the hit of the cancel we have to remove the people picker from the main view.
Step 4: Select the AppDelegate.m file and add the ReteriveSingleData view to the iPhone window here’s the code to do that
#import "AddressBookAppDelegate.h"
#import "RetriveSingleData.h"

@implementation AddressBookAppDelegate

@synthesize window;

- (void)applicationDidFinishLaunching:(UIApplication *)application {   

    // Override point for customization after application launch
        RetriveSingleData *retrieveVC = [[RetriveSingleData alloc]init];   
        [window addSubview: retrieveVC.view];
        [window makeKeyAndVisible];
}
Step 5: Run the application, to see the output, which would look some what like this
Output
Selected Record
I hope that this post was helpful for you in learning on how to get the data from the address book inside your application, Happy iCoding and have a great Day.

Friday 29 June 2012

Adding UIButton on Navigation Bar


In this post we will have a look at something called as UIBarButtonItem

Design Phase:We will have two objects of UIBarButtonItem in the Navigation Bar and will try to change the background color of the view when an appropriate BarButton will be selected. 
So for this demo we will need two objects of UIBarButtonItem, and a Navigation Controller as the bar buttons will be placed in the navigation bar. So here's how our final design will look like

Final Design


Step 1: Open Xcode create a new project and save it with an appropriate name, now add a UIViewController subclass file and save it with the name myviewController

Step 2: Go to the .h file of myviewController and declare the objects of UIBarButtonItem class and of course we will be requiring two methods which will change the background color for us on the selection of the UIBarButtonItem, so here's how everything looks so far

@interface myviewController : UIViewController {

UIBarButtonItem *leftbarButton,*rightbarButton;
}
-(void) leftbarMethod;
-(void) rightbarMethod;

@end


Step 3: now go to the .m file of the myviewController class and select its init method and add this piece of code

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
// Custom initialization

//setting the text and functions for the UIBarButtonItem

leftbarButton = [[UIBarButtonItem alloc]initWithTitle:@"Black"style:UIBarButtonItemStylePlain target:self action:@selector(leftbarMethod)];

rightbarButton = [[UIBarButtonItem alloc]initWithTitle:@"Red"style:UIBarButtonItemStylePlain target:self action:@selector(rightbarMethod)];

//setting the bar button items for the navigation controller

self.navigationItem.leftBarButtonItem = leftbarButton;

self.navigationItem.rightBarButtonItem = rightbarButton;

//setting the title of the view

self.title= @"Bar button";
}
return self;
}

The above code is quite self explanatory what I have done is I have allocated memory for both the UIBarButtonItem and in my next step I have added those barbutton item to the navigationbar using the navigationItem property of the UIViewController.

Now about those two methods well they are also quite easy and here's the code that they contain

-(void) leftbarMethod
{

//changing the back ground color of the view
[self.view setBackgroundColor:[UIColor blackColor]];
}
-(void) rightbarMethod
{
//changing the back ground color of the view
[self.view setBackgroundColor:[UIColor redColor]];

}


Step 4: Now all you have to do is add this view to your main window by going into the AppDelegate.m file and this is how you will do that

#import "UIBarDemoAppDelegate.h"
#import "myviewController.h"

@implementation UIBarDemoAppDelegate

@synthesize window;


- (void)applicationDidFinishLaunching:(UIApplication *)application {

// Override point for customization after application launch
myviewController *obj = [[myviewController alloc]init];

UINavigationController *nav = [[UINavigationControlleralloc]initWithRootViewController:obj];

[window addSubview:nav.view];

[window makeKeyAndVisible];
}

In the above code you are creating the object of myviewController class and in the next line you are creating the object of UINavigationController and suppling the details of the root view controller which will appear when the application runs.

Step 5: Press Build and Go and you will get the following output





i hope this post was helpful for you, Happy iCoding and have a great Day.