Need a Facebook App ID before you create a new project with the SDK.


You will need a Facebook App ID before you create a new project with the SDK.

1. Create a new app on the Facebook App Dashboard, enter your app's basic information.




Once created, note the app ID shown at the top of the dashboard page. 




Alternatively, you can of course use the ID of an existing app.
Now, you need to set the Bundle Identifier and configure your Facebook application to support login from an iOS application.
(Note: this is a new step in the Facebook SDK for iOS v3.1. Previous versions of the SDK did not require this step.)
Click on the checkmark next to “Native iOS App” and supply your Bundle Identifier in the “Bundle ID” field. In addition, make sure the Facebook Login radio button is set to “Enabled”.


You can find or set your Bundle Identifier in Xcode in the Project tab.


3. Configure a new Xcode Project

Create a new Xcode project, add the Facebook SDK for iOS, its dependencies, and the Facebook App ID to its settings

In Xcode, create a new project, and select 'Single View Application' as shown below.






Provide a name and identifier as required:



Adding SDK, framework dependencies

Add the Facebook SDK for iOS Framework by dragging the FacebookSDK.framework folder from the SDK installation folder into the Frameworks section of your Project Navigator.




Choose 'Create groups for any added folders' and deselect 'Copy items into destination group's folder (if needed)' to keep the reference to the SDK installation folder, rather than creating a copy.



Add the Facebook SDK for iOS resource bundle by dragging the FacebookSDKResources.bundle file from theFacebookSDK.framework/Resources folder into the Frameworks section of your Project Navigator.








As you did when copying the Framework, choose 'Create groups for any added folders' and deselect 'Copy items into destination group's folder (if needed)'

You can also add the FBUserSettingsViewResources bundle in the same way if you expect to use that controller in your app.

The SDK relies on three other frameworks (AdSupport, Accounts and Social) to use the Facebook features built into iOS6. To add these, go to the 'Linked Frameworks and Libraries' section of the target's Summary pane, and click the 'plus' button to add them:



Note: You should use the 'Optional' flag for iOS6-specific frameworks if you would like your app to also build for older versions of the operating systems.




Once done, your Project Navigator should look something like this:


 

Adding SQLite

Next you need to add the ''-lsqlite3.0'' SQL library to the list of build dependencies in the Build Settings pane:





 


 

 

 

Adding your Facebook App ID

Finally, you need to place the Facebook app ID in two places in your application's main .plist file. Create a key called FacebookAppID with a string value, and add the app ID there:





Also, create an array key called URL types with a single array sub-item called URL Schemes. Give this a single item with your app ID prefixed withfb:




How to upload images with text using iPhone SDK using ASIHttpRequest ?

Code .h file.
#import

@interface RootViewController : UIViewController {
   
    NSMutableArray *arrImages;
    IBOutlet UIButton *btnImage1;
    IBOutlet UIButton *btnImage2;
    IBOutlet UIButton *btnImage3;
    IBOutlet UIButton *btnImage4;
}

- (IBAction)btnTakePicture_Clicked:(id)sender;
- (IBAction)btnPostImages_Clicked:(id)sender;
@end
Code .m file.
#import "RootViewController.h"
#import "ASIFormDataRequest.h"

@implementation RootViewController
int intButton;

#pragma mark -
#pragma mark View lifecycle


- (void)viewDidLoad {
    [super viewDidLoad];

    self.title = @"Select Images";
    arrImages = [[NSMutableArray alloc]init];
}

- (IBAction)btnTakePicture_Clicked:(id)sender
{
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"Select Image from..." delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:nil otherButtonTitles:@"Camera", @"Image Gallary", nil];
    actionSheet.actionSheetStyle = UIActionSheetStyleBlackTranslucent;
    actionSheet.alpha=0.90;
    actionSheet.tag = 1;
    [actionSheet showInView:self.view];
    [actionSheet release];
    UIButton *btn = (UIButton *)sender;
    intButton = btn.tag;
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    switch (actionSheet.tag)
    {
        case 1:
            switch (buttonIndex)
        {
            case 0:
            {               
#if TARGET_IPHONE_SIMULATOR
               
                UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"Message" message:@"Camera not available." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
                [alert show];
                [alert release];
               
#elif TARGET_OS_IPHONE   
               
                UIImagePickerController *picker = [[UIImagePickerController alloc] init]; 
                picker.sourceType = UIImagePickerControllerSourceTypeCamera; 
                picker.delegate = self; 
                //picker.allowsEditing = YES; 
                [self presentModalViewController:picker animated:YES];
                [picker release];
               
#endif   
            }
                break;
            case 1:
            {
                UIImagePickerController *picker = [[UIImagePickerController alloc] init]; 
                picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary; 
                picker.delegate = self; 
                [self presentModalViewController:picker animated:YES];
                [picker release];
            }
                break;
        }
            break;
           
        default:
            break;
    }   
}

-(void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary*)info
{
    NSData *dataImage = UIImageJPEGRepresentation([info objectForKey:@"UIImagePickerControllerOriginalImage"],1);
    UIImage *img = [[UIImage alloc] initWithData:dataImage];

    if (intButton == 1) {
        [btnImage1 setBackgroundImage:img forState:UIControlStateNormal];
        [btnImage1 setImage:nil forState:UIControlStateNormal];
    }
    else if (intButton == 2) {
        [btnImage2 setBackgroundImage:img forState:UIControlStateNormal];
        [btnImage2 setImage:nil forState:UIControlStateNormal];
    }
    else if (intButton == 3) {
        [btnImage3 setBackgroundImage:img forState:UIControlStateNormal];
        [btnImage3 setImage:nil forState:UIControlStateNormal];
    }
    else {
        [btnImage4 setBackgroundImage:img forState:UIControlStateNormal];
        [btnImage4 setImage:nil forState:UIControlStateNormal];
    }
    [arrImages addObject:dataImage];
    [picker dismissModalViewControllerAnimated:YES];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
   
    [self.navigationController dismissModalViewControllerAnimated:YES];   
}

- (IBAction)btnPostImages_Clicked:(id)sender {
   
    if ([arrImages count] > 0) {
        NSString *strURL = @"Write Your URL Here.";
        ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:strURL]];
        [request setDelegate:self];
        [request setPostValue:@"This is sample text..." forKey:@"text"];
        for (int i = 0; i < [arrImages count]; i++) {
            [request addData:[arrImages objectAtIndex:i] withFileName:@"image.jpg" andContentType:@"image/jpeg" forKey:[NSString stringWithFormat:@"image%d", i + 1]];
        }   
        [request startAsynchronous];
    }
    else {
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"Message" message:@"Please select images..." delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
        [alertView show];
        [alertView release];
    }
}

- (void)requestFinished:(ASIHTTPRequest *)request {
   
    NSString *receivedString = [request responseString];
    UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"Message" message:receivedString delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil];
    [alertView show];
    [alertView release];
}
- (void)requestFailed:(ASIHTTPRequest *)request {
   
    NSString *receivedString = [request responseString];
    UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"Message" message:receivedString delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
    [alertView show];
    [alertView release];
}

#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
   
    // Relinquish ownership any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
    // For example: self.myOutlet = nil;
}


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


@end 


                                    Click here for code

How to draw a pie chart using iPhone sdk?

Here’s one way to draw a PIE chart using the latest iPhone SDK. There are a ton of tutorials out there that let you get started with the iPhone app development itself and I am by no means any authoritative source on learning how to develop one. Having said that, here’s a class file that will help you use the UIKit and Quartz to draw vector graphics. 

GraphView.h

1
2
3
4
5
6
7
8
9
10
11
12
#
#(nothing to see here)
#
 
#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
 
@interface GraphView : UIView {
 
}
 
@end
GraphView.m

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#import "GraphView.h"
 
#define PI 3.14159265358979323846
static inline float radians(double degrees) { return degrees * PI / 180; }
 
@implementation GraphView
 
- (void)drawRect:(CGRect)rect {
 
 CGRect parentViewBounds = self.bounds;
 CGFloat x = CGRectGetWidth(parentViewBounds)/2;
 CGFloat y = CGRectGetHeight(parentViewBounds)*0.55;
 
    // Get the graphics context and clear it
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    CGContextClearRect(ctx, rect);
 
 // define stroke color
 CGContextSetRGBStrokeColor(ctx, 1, 1, 1, 1.0);
 
 // define line width
 CGContextSetLineWidth(ctx, 4.0);
 
 
       // need some values to draw pie charts
 
        double snapshotCapacity =20;
        double rawCapacity = 100;
        double systemCapacity = 1;
 
 int offset = 5;
 double pie1_start = 315.0; 
 double pie1_finish = snapshotCapacity *360.0/rawCapacity; 
 double system_finish = systemCapacity*360.0/rawCapacity;
 
    CGContextSetFillColor(ctx, CGColorGetComponents( [[UIColor greenColor] CGColor]));
    CGContextMoveToPoint(ctx, x+2*offset, y);     
    CGContextAddArc(ctx, x+2*offset, y, 100,  radians(snapshot_start), radians(snapshot_start+snapshot_finish), 0); 
    CGContextClosePath(ctx); 
    CGContextFillPath(ctx); 
 
 // system capacity 
 CGContextSetFillColor(ctx, CGColorGetComponents( [[UIColor colorWithRed:15 green:165/255 blue:0 alpha:1 ] CGColor]));
 CGContextMoveToPoint(ctx, x+offset,y);     
    CGContextAddArc(ctx, x+offset, y, 100,  radians(snapshot_start+snapshot_finish+offset), radians(snapshot_start+snapshot_finish+system_finish), 0); 
    CGContextClosePath(ctx); 
    CGContextFillPath(ctx); 
 
 /* data capacity */
 CGContextSetFillColor(ctx, CGColorGetComponents( [[UIColor colorWithRed:99/255 green:184/255 blue:255/255 alpha:1 ] CGColor]));
 CGContextMoveToPoint(ctx, x, y);     
    CGContextAddArc(ctx, x, y, 100,  radians(snapshot_start+snapshot_finish+system_finish+offset), radians(snapshot_start), 0); 
    CGContextClosePath(ctx); 
    CGContextFillPath(ctx); 
}
                                                                 click here for source code

How to validate email id in iPhone SDK?

This is prefect method to validate email address valid or not. In this method I'm using "NSPredicate" and "Name Regex" to validate email-ID

NSString *email = textFieldemail.text;
NSString *emailRegEx =
@"(?:[a-z0-9!#$%\\&'*+/=?\\^_`{|}~-]+(?:\\.[a-z0-9!#$%\\&'*+/=?\\^_`{|}"
@"~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\"
@"x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[a-z0-9](?:[a-"
@"z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5"
@"]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-"
@"9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21"
@"-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])";

NSPredicate *regExPredicate =
[NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegEx];
BOOL myStringMatchesRegEx = [regExPredicate evaluateWithObject:email];


if(!myStringMatchesRegEx)
{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"email" message:@"invalid email-ID, please provide a valid email id." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
[alert release];
}
else
[self prepareHmlDataAndSendEmail];
 
This is another one of  a simplest method to validate an email id on a text box in iphone development
 
if (! (([txtMailId.text rangeOfString:@"@"].location != NSNotFound) && ([txtMailId.text rangeOfString:@"."].location != NSNotFound) && [txtMailId.text rangeOfString:@"@"].location < [txtMailId.text rangeOfString:@"."].location ) )
{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"email" message:@"invalid email-ID, please enter a valid email id." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
[alert release];
}
else
[self prepareHmlDataAndSendEmail];  
 
 

How to use nsxmlparser in Iphone SDk?


NSXMLParser is a forward only reader or an event driven parser. What it means is, an event is raised whenever the parser comes across a start of an element, value, CDATA and so on. The delegate of NSXMLParser can then implement these events to capture XML data. Some of the events are raised multiple times like the start of an element, value of an element and so on. Since NSXMLParser is known as an event driven parser, we can only read data at the present node and cannot go back. The iPhone only supports NSXMLParser and not NSXMLDocument, which loads the whole XML tree in memory.
Books Application

To understand how to use an instance of NSXMLParser, let’s create a simple navigation based application where we will list the title of the book in the table view and upon selecting a title, display the detail information in a detail view. Click here to see the sample XML file, used in this application.
Create a new application in XCode by selecting Navigation-Based Application, I have named my app XML. Since the NSXMLParser is a forward only parser or an event driven parser, we need to store the data locally, which can be used later. To store this data, we will create a class which replicates the elements and attributes in the XML file. An instance of this class represents one single Book element in the XML file. I have named this class “Book” and its source code is listed below
//Book.h
#import <UIKit/UIKit.h>

@interface Book : NSObject {

NSInteger bookID;
NSString *title; //Same name as the Entity Name.
NSString *author; //Same name as the Entity Name.
NSString *summary; //Same name as the Entity Name.

}

@property (nonatomic, readwrite) NSInteger bookID;
@property (nonatomic, retain) NSString *title;
@property (nonatomic, retain) NSString *author;
@property (nonatomic, retain) NSString *summary;

@end

//Book.m
#import "Book.h"

@implementation Book

@synthesize title, author, summary, bookID;

- (void) dealloc {

[summary release];
[author release];
[title release];
[super dealloc];
}

@end
Notice that the name of the property is the same as the element name in the XML file. Since the XML file has n number of Book elements, we need an array to hold all the books we read, so we declare an array in the application delegate and this is how the source code changes
//XMLAppDelegate.h
#import <UIKit/UIKit.h>

@interface XMLAppDelegate : NSObject &lt;UIApplicationDelegate&gt; {

UIWindow *window;
UINavigationController *navigationController;

NSMutableArray *books;
}

@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) IBOutlet UINavigationController *navigationController;

@property (nonatomic, retain) NSMutableArray *books;

@end
The Delegate

To keep the source code clean, we will also declare a delegate, which will be used by the instance of NSXMLParser and this how its source code looks like
//XMLParser.h
#import <UIKit/UIKit.h>

@class XMLAppDelegate, Book;

@interface XMLParser : NSObject {

NSMutableString *currentElementValue;

XMLAppDelegate *appDelegate;
Book *aBook;
}

- (XMLParser *) initXMLParser;

@end
Let’s look at how the variables will be used. currentElementValue holds the current element value, appDelegate so we can access the array which holds the list of books and finally a reference to the Book class itself. Notice that we do not keep track of the current element name being processed, because the event will tell us that. Finally, we have a constructor called initXMLParser and let’s see what it does
//XMLParser.m
- (XMLParser *) initXMLParser {

[super init];

appDelegate = (XMLAppDelegate *)[[UIApplication sharedApplication] delegate];

return self;
}
Very simple, gets a reference to the application delegate and returns itself.
Parsing the XML File

Now that we have everything set up, let’s look at the code to read the XML file
//XMLAppDelegate.m
- (void)applicationDidFinishLaunching:(UIApplication *)application {

NSURL *url = [[NSURL alloc] initWithString:@"http://sites.google.com/site/iphonesdktutorials/xml/Books.xml"];
NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithContentsOfURL:url];

//Initialize the delegate.
XMLParser *parser = [[XMLParser alloc] initXMLParser];

//Set delegate
[xmlParser setDelegate:parser];

//Start parsing the XML file.
BOOL success = [xmlParser parse];

if(success)
NSLog(@"No Errors");
else
NSLog(@"Error Error Error!!!");

// Configure and show the window
[window addSubview:[navigationController view]];
[window makeKeyAndVisible];
}
The code is very simple, we create an instance of NSURL, create an instance of NSXMLParser, initialize the delegate, assign the delegate and start parsing by passing the parse message. It returns YES, if the parsing is successful, NO if there is an error or if the operation is aborted.



Parsing the start of an element

The delegate of the parser does not have to implement all the methods that it raises, so we can pick and choose which events we care about. If we do not want to handle the event when the parser starts reading the document, we can choose to ignore it by not implementing it. We will only implement three methods which is called when the parser encounters the start of an element, end of an element or value of an element.
Let’s look at parser:didStartElement:namespaceURI:qualifiedName:attributes method which is called when the parser encounters the start of an element.
//XMLParser.m
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName
attributes:(NSDictionary *)attributeDict {

if([elementName isEqualToString:@"Books"]) {
//Initialize the array.
appDelegate.books = [[NSMutableArray alloc] init];
}
else if([elementName isEqualToString:@"Book"]) {

//Initialize the book.
aBook = [[Book alloc] init];

//Extract the attribute here.
aBook.bookID = [[attributeDict objectForKey:@"id"] integerValue];

NSLog(@"Reading id value :%i", aBook.bookID);
}

NSLog(@"Processing Element: %@", elementName);
}
From the above code we first initialize the array when it encounters the “Books” element, which can also be done in parserDidStartDocument method. If the element is “Book” then we initialize the local book object and read the attribute of the present XML book element from the attribute dictionary object.
Parsing an element’s value

Now that we have a local book object representing the current book element in the XML tree, the next thing to do is to populate the local object with the XML data. The parser now moves to the title element and the same method is called again, but this time we do not do anything. Parser then moves to the element value and it sends parser:foundCharacters event to the delegate, let’s see how the code look like
//XMLParser.m
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {

if(!currentElementValue)
currentElementValue = [[NSMutableString alloc] initWithString:string];
else
[currentElementValue appendString:string];

NSLog(@"Processing Value: %@", currentElementValue);

}
The code is very easy to read, if the mutable string is nil then we initialize it with the string parameter. If the currentElementValue is not nil then we simply append the data to the existing string value.
Parsing the end of an element

The parser now moves to the end of the element and hence parser:didEndElement:namespaceURI:qualifiedName is sent to the delegate. This is where we set the currentElementValue to the correct property of the local book object and set the currentElementValue to nil. This is how the code looks like
//XMLParser.m
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {

if([elementName isEqualToString:@"Books"])
return;

//There is nothing to do if we encounter the Books element here.
//If we encounter the Book element howevere, we want to add the book object to the array
// and release the object.
if([elementName isEqualToString:@"Book"]) {
[appDelegate.books addObject:aBook];

[aBook release];
aBook = nil;
}
else
[aBook setValue:currentElementValue forKey:elementName];

[currentElementValue release];
currentElementValue = nil;
}
If the element it encounters is “Books” then there is nothing to do as we are almost done reading the file. If the element name is “Book” then we add the book object to the array and set the local book object to nil and release its memory, so it can be used again. If the end element is not “Books” or “Book” then it must be one of the sub element of “book” and we set the currentElementValue to the current book property using setValue:forKey. We can do this, because the properties declared in the book is the same as the XML element names.
The cycle starts again by initializing the book object and reading the attribute, reading the children elements and setting its value to the local object and finally adding the object to the array. The parser calls the three functions again and again as long as it does not encounters eof.
Complete listing of XMLParser.m file
//XMLParser.m
#import "XMLParser.h"
#import "XMLAppDelegate.h"
#import "Book.h"

@implementation XMLParser

- (XMLParser *) initXMLParser {

[super init];

appDelegate = (XMLAppDelegate *)[[UIApplication sharedApplication] delegate];

return self;
}

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName
attributes:(NSDictionary *)attributeDict {

if([elementName isEqualToString:@"Books"]) {
//Initialize the array.
appDelegate.books = [[NSMutableArray alloc] init];
}
else if([elementName isEqualToString:@"Book"]) {

//Initialize the book.
aBook = [[Book alloc] init];

//Extract the attribute here.
aBook.bookID = [[attributeDict objectForKey:@"id"] integerValue];

NSLog(@"Reading id value :%i", aBook.bookID);
}

NSLog(@"Processing Element: %@", elementName);
}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {

if(!currentElementValue)
currentElementValue = [[NSMutableString alloc] initWithString:string];
else
[currentElementValue appendString:string];

NSLog(@"Processing Value: %@", currentElementValue);

}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {

if([elementName isEqualToString:@"Books"])
return;

//There is nothing to do if we encounter the Books element here.
//If we encounter the Book element howevere, we want to add the book object to the array
// and release the object.
if([elementName isEqualToString:@"Book"]) {
[appDelegate.books addObject:aBook];

[aBook release];
aBook = nil;
}
else
[aBook setValue:currentElementValue forKey:elementName];

[currentElementValue release];
currentElementValue = nil;
}

- (void) dealloc {

[aBook release];
[currentElementValue release];
[super dealloc];
}
                                                                   click here for code