Monday, 17 March 2014

                             





                              This is the post, to know basics to connect your IOS mobile app connect to Facebook app and get That User details.


                                   Open your XCode and crete new application and select single window application

         
                                     give name like FacebookConnection

                               
                                    and finish it, it will create a default application like 



                                    Here we are going to use Parse frame work for that got parse.com.  Create a new account on parse or login using your Github account , After login Create a new App with your app name and it will create
Application ID
Client Key

Javascript Key
.NET Key
REST API Key
Master Key


copy that   Application ID, Client Key.

              Download your ios parse api from https://www.parse.com/docs/downloads

             It will download Parse.framework.zip file extract that file you will get Parse.framework folder.

                      Open your XCode FacebookConnection  project and Add parse Framework to your project

Select your parse.framework (Tick for the option Copy items into destination groups).

You will see that parse framework on your Xcode left panel .

      
                                   Select Facebookconnection file in your Xcode left panel


                                   Take Buildphase tab and Link binary with libraries with option

                             Here you can see the Parse.framework package, otherwise drag&drop from left panel .



                                   add #import <Parse/Parse.h>

                                   Next open you AppDelegate.m file in your - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

method add these two lines of code

[Parse setApplicationId:@"YOUR APPLICATION ID" clientKey:@"YOUR CLIENTKEY"];

(you have already copied the application id and client key from parse web site).
 


The parse framework configuration all most all completed except small steps.


Now we have to  configure Facebook framework to your app

For that fallow below steps

Step 1: Install the Facebook SDK for iOS

First download https://developers.facebook.com/resources/facebook-ios-sdk-current.pkg

The default install location is ~/Documents/FacebookSDK


 Step 2: Obtain a Facebook App ID

If you haven't already registered your app with Facebook by creating a Facebook app, you can create a new app on the App Dashboard. In the App Dashboard, select Apps > Create an app:


And fill in the information:
Once your app is created, or if you already had a Facebook app, the app ID is shown at the top of the dashboard page.
NOTE: If you already have a Facebook app (and corresponding Facebook app ID) that you're using for the same app in another platform (for example, Android), you can use the same app ID for iOS.


                                     Next, you need to set the Bundle Identifier and configure your Facebook application to support login from an iOS application.

Select "Settings" from the left-hand nav. Inside the settings, click on "Add Platform" and choose "iOS". Then provide your Bundle Identifier in the "Bundle ID" field and enable "Single Sign On". Don't forget to save the changes!



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



Step 3: Configure your Xcode Project

Add the Facebook SDK for iOS to your project and configure your .plist file

Add the Facebook SDK

The Facebook SDK for iOS is a framework that you add to your Xcode project. To add the SDK, open ~/Documents/FacebookSDK and drag the FacebookSDK.framework 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 reference the SDK where it was installed rather than copying the SDK into your app.



The SDK will automatically load its framework and resource dependencies.

Configure the .plist

Follow these three steps:



Create a key called FacebookAppID with a string value, and add the app ID there.
Create a key called FacebookDisplayName with a string value, and add the Display Name you configured in the App Dashboard.
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 with fb. This is used to ensure the application will receive the callback URL of the web-based OAuth flow.
The finished .plist should look something like this:





After this, Facebook setting also compleated.


                                  Now we have to integrate facebook and parse for that you have to copy your facebook id (EX : 527250924888393)


                               Open your parse.com/apps  and select your app





select settings tab


select User authentication option from left panel





in that set Facebook Application id and switch on the button




                                    Open your AppDelegate.m  file and add [PFFacebookUtils initializeFacebook]; line to method  - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

after that [FBSession.activeSession handleDidBecomeActive]; line to method - (void)applicationDidBecomeActive:(UIApplication *)application


[FBSession.activeSession close]; line to method - (void)applicationWillTerminate:(UIApplication *)application

and finally add the method

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
    return [PFFacebookUtils handleOpenURL:url];
}



The basic settings for integrating parse framework and Facebook framework has completed . 



Set permissions required from the facebook user account

 // Set permissions required from the facebook user account
    NSArray *permissionsArray = @[ @"user_about_me", @"email", @"user_birthday", @"friends_birthday", @"friends_about_me", @"user_photos", @"user_videos", @"publish_stream"];
    //NSLog(@"Permissions array %@", permissionsArray);
    if ([PFUser currentUser] && // Check if a user is cached
        [PFFacebookUtils isLinkedWithUser:[PFUser currentUser]]) // Check if user is linked to Facebook
    {
        // Push the next view controller without animation
            
    }
   
    // Login PFUser using facebook
    else
    {
        [PFFacebookUtils logInWithPermissions:permissionsArray block:^(PFUser *user, NSError *error)
         {
            
             // [_activityIndicator stopAnimating]; // Hide loading indicator
            
             if (!user)
             {
                 if (!error)
                 {
                     NSLog(@"Uh oh. The user cancelled the Facebook login.");
                    
                     UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Log In Error" message:@"Uh oh. The user cancelled the Facebook login." delegate:nil cancelButtonTitle:nil otherButtonTitles:@"Dismiss", nil];
                    [alert show];
                     NSMutableDictionary *errorMessage = [[NSMutableDictionary alloc] initWithObjectsAndKeys:@"error", @"status", @"The user cancelled the Facebook login", @"description",nil];
                                     }
                 else
                 {
                     NSMutableDictionary *errorMessage = [[NSMutableDictionary alloc] initWithObjectsAndKeys:@"error", @"status", error.description, @"description", nil];
                    
                     NSLog(@"Uh oh. An error occurred: %@", error);
                     UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Log In Error" message:[error description] delegate:nil cancelButtonTitle:nil otherButtonTitles:@"Dismiss", nil];
                     [alert show];
                    
                 }
             }
             else if (user.isNew)
             {
                 NSLog(@"User with facebook signed up and logged in!");
                
                 //[self.navigationController pushViewController:[[UserDetailsViewController alloc] initWithStyle:UITableViewStyleGrouped] animated:YES];
                 //[self presentViewController:[[UserDetailsViewController alloc] initWithStyle:UITableViewStyleGrouped] animated:YES completion:nil];
             }
             else
             {
                 NSLog(@"User with facebook logged in!");
                 [self requestMe];
                 //[self.navigationController pushViewController:[[UserDetailsViewController alloc] initWithStyle:UITableViewStyleGrouped] animated:YES];
                 //[self presentViewController:[[UserDetailsViewController alloc] initWithStyle:UITableViewStyleGrouped] animated:YES completion:nil];
             }
         }];
    }
   
    // [_activityIndicator startAnimating]; // Show loading indicator until login is finished
}


this will open the Facebook login prompt

 

Get user details from Facebook

[FBRequestConnection startForMeWithCompletionHandler:^(FBRequestConnection *connection,
                                                           NSDictionary<FBGraphUser> *me,
                                                           NSError *error) {
        if(error) {
            [self printError:@"Error requesting /me" error:error];
            return;
        }
        //NSLog(@"Me dictionary %@", me.dictionary);
        NSArray *keys = me.allKeys;
        NSArray *values = me.allValues;
        userInfo = [[NSMutableDictionary alloc] init];
        //[userInfo setObject:[values valueForKey:@"email"] forKey:@"email"];
        //[userInfo setObject:[values valueForKey:@"id"] forKey:@"id"];
       
        for (int incr = 0; incr < keys.count; incr++) {
            NSLog(@"Me  %d Key %@ Value %@", incr ,[keys objectAtIndex:incr], [values objectAtIndex:incr]);
                   }
        NSLog(@"My name is %@", me.name);
        NSLog(@"*#*#*#*#*#*#_________User information is %@",userInfo);
           }];


Get Facebook friends List

        NSString* fql =
        @"{"
        @"'allfriends':'SELECT uid2 FROM friend WHERE uid1=me()',"
        @"'frienddetails':'select birthday, birthday_date, name, uid, pic_square,username from user where uid in (select uid2 from friend where uid1=me()) order by name',"
        @"}";
       
        [FBRequestConnection startWithGraphPath:@"/fql"
                                     parameters:@{ @"q" : fql}
                                     HTTPMethod:@"GET"
                              completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
                                  if(error) {
                                      //[self printError:@"Error Occured. Please Try Again Latter..!" error:error];
                                                                       }
                                 
                                  NSMutableArray* friends = [[NSMutableArray alloc]init];
                                 
                                  NSArray* friendInfo = ((NSArray*)[result data])[1][@"fql_result_set"];
//                                  facebookCount = [friendInfo count];
                                  if([friendInfo count]>0)
                                  {
                                  for(long i = 0; i < [friendInfo count]; i++) {
                                      NSDictionary* friend = [[NSDictionary alloc]initWithObjectsAndKeys:
                                                              [[friendInfo objectAtIndex:i] objectForKey:@"uid"], @"uid",
                                                              [[friendInfo objectAtIndex:i] objectForKey:@"birthday"], @"birthday",
                                                              [[friendInfo objectAtIndex:i] objectForKey:@"name"], @"name",
                                                              [[friendInfo objectAtIndex:i] objectForKey:@"pic_square"], @"pic_square",
                                                              [[friendInfo objectAtIndex:i] objectForKey:@"username"], @"username", nil];
                                     
                                      [friends addObject:friend];
                                  }
                                                                   }
                                  else
                                  {
                                                                        }
                              }];