add the Facebook sdk in our project
add FacebookAppID in property list
In Appdelegate.h
#import <UIKit/UIKit.h>
#import <FacebookSDK/FacebookSDK.h>
@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
- (void)sessionStateChanged:(FBSession *)session state:(FBSessionState) state error:(NSError *)error;
- (void)userLoggedIn;
- (void)userLoggedOut;
@end
In Appdelegate.m
//
// AppDelegate.m
// shareAndLoginFB
//
// Created by Regius on 11/09/14.
// Copyright (c) 2014 Regius. All rights reserved.
//
#import "AppDelegate.h"
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Load the FBLoginView class (needed for login)
[FBLoginView class];
// Load the FBProfilePictureView
// You can find more information about why you need to add this line of code in our troubleshooting guide
[FBProfilePictureView class];
// Override point for customization after application launch.
// Whenever a person opens the app, check for a cached session
if (FBSession.activeSession.state == FBSessionStateCreatedTokenLoaded) {
NSLog(@"Found a cached session");
// If there's one, just open the session silently, without showing the user the login UI
[FBSession openActiveSessionWithReadPermissions:@[@"basic_info"]
allowLoginUI:NO
completionHandler:^(FBSession *session, FBSessionStatestate, NSError *error) {
// Handler for session state changes
// This method will be called EACH time the session state changes,
// also for intermediate states and NOT just when the session open
[self sessionStateChanged:session state:state error:error];
}];
// If there's no cached session, we will show a login button
} else {
NSLog(@"not login inFB");
}
return YES;
}
// This method will handle ALL the session state changes in the app
- (void)sessionStateChanged:(FBSession *)session state:(FBSessionState) state error:(NSError *)error
{
// If the session was opened successfully
if (!error && state == FBSessionStateOpen){
NSLog(@"Session opened");
// Show the user the logged-in UI
[self userLoggedIn];
return;
}
if (state == FBSessionStateClosed || state == FBSessionStateClosedLoginFailed){
// If the session is closed
NSLog(@"Session closed");
// Show the user the logged-out UI
[self userLoggedOut];
}
// Handle errors
if (error){
NSLog(@"Error");
NSString *alertText;
NSString *alertTitle;
// If the error requires people using an app to make an action outside of the app in order to recover
if ([FBErrorUtility shouldNotifyUserForError:error] == YES){
alertTitle = @"Something went wrong";
alertText = [FBErrorUtility userMessageForError:error];
[self showMessage:alertText withTitle:alertTitle];
} else {
// If the user cancelled login, do nothing
if ([FBErrorUtility errorCategoryForError:error] ==FBErrorCategoryUserCancelled) {
NSLog(@"User cancelled login");
// Handle session closures that happen outside of the app
} else if ([FBErrorUtility errorCategoryForError:error] ==FBErrorCategoryAuthenticationReopenSession){
alertTitle = @"Session Error";
alertText = @"Your current session is no longer valid. Please log in again.";
[self showMessage:alertText withTitle:alertTitle];
// For simplicity, here we just show a generic message for all other errors
} else {
//Get more error information from the error
NSDictionary *errorInformation = [[[error.userInfoobjectForKey:@"com.facebook.sdk:ParsedJSONResponseKey"]objectForKey:@"body"] objectForKey:@"error"];
// Show the user an error message
alertTitle = @"Something went wrong";
alertText = [NSString stringWithFormat:@"Please retry. \n\n If the problem persists contact us and mention this error code: %@", [errorInformationobjectForKey:@"message"]];
[self showMessage:alertText withTitle:alertTitle];
}
}
// Clear this token
[FBSession.activeSession closeAndClearTokenInformation];
// Show the user the logged-out UI
[self userLoggedOut];
}
}
// Show the user the logged-out UI
- (void)userLoggedOut
{
// Confirm logout message
[self showMessage:@"You're now logged out" withTitle:@""];
}
// Show the user the logged-in UI
- (void)userLoggedIn
{
// Set the button title as "Log out"
// Welcome message
[self showMessage:@"You're now logged in" withTitle:@"Welcome!"];
}
// Show an alert message
- (void)showMessage:(NSString *)text withTitle:(NSString *)title
{
[[[UIAlertView alloc] initWithTitle:title
message:text
delegate:self
cancelButtonTitle:@"OK!"
otherButtonTitles:nil] show];
}
- (BOOL)application:(UIApplication *)application
openURL:(NSURL *)url
sourceApplication:(NSString *)sourceApplication
annotation:(id)annotation
{
return [FBSession.activeSession handleOpenURL:url];
}
- (void)applicationDidBecomeActive:(UIApplication *)application
{
[FBAppCall handleDidBecomeActive];
}
In yourVIewController.h
#import <UIKit/UIKit.h>
#import <FacebookSDK/FacebookSDK.h>
@interface ViewController : UIViewController<FBLoginViewDelegate>
-(IBAction)shareWithFB:(id)sender;
-(IBAction)loginWithFB:(id)sender;
In yourVIewController.m
#pragma mark login with FB method
-(IBAction)loginWithFB:(id)sender
{
// If the session state is any of the two "open" states when the button is clicked
if (FBSession.activeSession.state == FBSessionStateOpen
|| FBSession.activeSession.state == FBSessionStateOpenTokenExtended) {
// Close the session and remove the access token from the cache
// The session state handler (in the app delegate) will be called automatically
[FBSession.activeSession closeAndClearTokenInformation];
// If the session state is not any of the two "open" states when the button is clicked
} else {
// Open a session showing the user the login UI
// You must ALWAYS ask for basic_info permissions when opening a session
[FBSessionopenActiveSessionWithReadPermissions:@[@"public_profile",@"user_friends"]
allowLoginUI:YES
completionHandler:
^(FBSession *session, FBSessionState state, NSError *error) {
// Retrieve the app delegate
AppDelegate* appDelegate = [UIApplication sharedApplication].delegate;
// Call the app delegate's sessionStateChanged:state:error method to handle session state changes
[appDelegate sessionStateChanged:session state:state error:error];
[[FBRequest requestForMe] startWithCompletionHandler:
^(FBRequestConnection *connection,
NSDictionary<FBGraphUser> *user,
NSError *error) {
if (!error) {
NSString *firstName = user.first_name;
NSString *lastName = user.last_name;
NSString *facebookId = user.id;
NSString *email = [user objectForKey:@"email"];
NSString *imageUrl = [[NSString alloc] initWithFormat:@"http://graph.facebook.com/%@/picture?type=large", facebookId];
NSLog(@"%@",email);
}
}];
}];
}
}
-(IBAction)shareWithFB:(id)sender
{
// Check if the Facebook app is installed and we can present the share dialog
FBShareDialogParams *params = [[FBShareDialogParams alloc] init];
params.link = [NSURLURLWithString:@"https://developers.facebook.com/docs/ios/share/"];
params.name = @"Sharing Tutorial";
params.caption = @"Build great social apps and get more installs.";
params.picture = [NSURL URLWithString:@"http://i.imgur.com/g3Qc1HN.png"];
params.description = @"Allow your users to share stories on Facebook from your app using the iOS SDK.";
// If the Facebook app is installed and we can present the share dialog
if ([FBDialogs canPresentShareDialogWithParams:params]) {
// Present share dialog
[FBDialogs presentShareDialogWithLink:params.link
name:params.name
caption:params.caption
description:params.description
picture:params.picture
clientState:nil
handler:^(FBAppCall *call, NSDictionary *results, NSError*error) {
if(error) {
// An error occurred, we need to handle the error
NSLog([NSString stringWithFormat:@"Error publishing story: %@", error.description]);
} else {
// Success
NSLog(@"result %@", results);
}
}];
// If the Facebook app is NOT installed and we can't present the share dialog
} else {
// FALLBACK: publish just a link using the Feed dialog
// Put together the dialog parameters
NSMutableDictionary *params = [NSMutableDictionarydictionaryWithObjectsAndKeys:
@"Sharing Tutorial", @"name",
@"Build great social apps and get more installs.", @"caption",
@"Allow your users to share stories on Facebook from your app using the iOS SDK.", @"description",
@"https://developers.facebook.com/docs/ios/share/", @"link",
@"http://i.imgur.com/g3Qc1HN.png", @"picture",
nil];
// Show the feed dialog
[FBWebDialogs presentFeedDialogModallyWithSession:nil
parameters:params
handler:^(FBWebDialogResult result, NSURL*resultURL, NSError *error) {
if (error) {
// An error occurred, we need to handle the error
NSLog([NSString stringWithFormat:@"Error publishing story: %@", error.description]);
} else {
if (result ==FBWebDialogResultDialogNotCompleted) {
// User canceled.
NSLog(@"User cancelled.");
} else {
// Handle the publish feed callback
NSDictionary *urlParams = [selfparseURLParams:[resultURL query]];
if (![urlParams valueForKey:@"post_id"]) {
// User canceled.
NSLog(@"User cancelled.");
} else {
// User clicked the Share button
NSString *result = [NSStringstringWithFormat: @"Posted story, id: %@", [urlParams valueForKey:@"post_id"]];
NSLog(@"result %@", result);
}
}
}
}];
}
}
// A function for parsing URL parameters returned by the Feed Dialog.
- (NSDictionary*)parseURLParams:(NSString *)query {
NSArray *pairs = [query componentsSeparatedByString:@"&"];
NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
for (NSString *pair in pairs) {
NSArray *kv = [pair componentsSeparatedByString:@"="];
NSString *val =
[kv[1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
params[kv[0]] = val;
}
return params;
}