Facebook SDK iOS access code issue - ios

My Project is to get Facebook Insights data of my Fanpage on my iPhone App.
I started by installing Facebook SDK for iOS to get Access Code & than using SampleLoginSample Sample Program provided with Facebook iOS SDK.
Its working Perfect & giving same response as in Facebook API Explporer for Query
[self.textNoteOrLink setText:
[NSString stringWithFormat:#"https://graph.facebook.com/[PAGEID]?fields=likes&access_token=%#",appDelegate.session.accessTokenData.accessToken]];
but if i am writing below Query its not giving me response as in Facebook Explorer API
QUERY:
[self.textNoteOrLink setText:
[NSString stringWithFormat:#"https://graph.facebook.com/PAGEID/insights/page_fans?access_token=%#",appDelegate.session.accessTokenData.accessToken]];
RESPONSE:
{"data":[
],"paging":{
"previous":"https:\/\/graph.facebook.com\/PAGEID\/insights\/page_fans?access_token=CAA...snip...h2l&since=1378984583&until=1379243783","next":"https:\/\/graph.facebook.com\/PAGEID\/insights\/page_fans?access_token=CAA...snip...h2l&since=1379502983&until=1379762183"}}
Can anyone help me to get access code with get_insights permission in Facebook iOS SDK?

In SLAppDelegate.h
Under the list of #property, add:
-(BOOL)openSessionWithAllowLoginUI:(BOOL)allowLoginUI;
In SLAppDelegate.m
Under applicationDidBecomeActive, add:
/*
* Opens a Facebook session and optionally shows the login UX.
*/
- (BOOL)openSessionWithAllowLoginUI:(BOOL)allowLoginUI {
NSArray *permissions = [[NSArray alloc] initWithObjects:
#"read_insights",
nil];
return [FBSession openActiveSessionWithReadPermissions:permissions
allowLoginUI:allowLoginUI
completionHandler:^(FBSession *session,
FBSessionState state,
NSError *error) {
[self sessionStateChanged:session
state:state
error:error];
}];
}
And:
/*
* Callback for session changes.
*/
- (void)sessionStateChanged:(FBSession *)session
state:(FBSessionState) state
error:(NSError *)error
{
switch (state) {
case FBSessionStateOpen:
if (!error) {
// We have a valid session
NSLog(#"User session found");
}
break;
case FBSessionStateClosed:
case FBSessionStateClosedLoginFailed:
[FBSession.activeSession closeAndClearTokenInformation];
break;
default:
break;
}
if (error) {
UIAlertView *alertView = [[UIAlertView alloc]
initWithTitle:#"Error"
message:error.localizedDescription
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];
}
}
In SLViewController.h
At the end of viewDidLoad , add:
[appDelegate openSessionWithAllowLoginUI:NO];

Related

how to Use Default LoginWithFacebook Button in my code

here is my code which is running properly but I want to use LoginWithFacebook default button which is provided by facebook.
Is there any image provided by facebook then please give me suggestion.
thankx in advance.....
#import "FacebbokViewController.h"
#import "UserAppAppDelegate.h"
#interface FacebbokViewController ()
#end
#implementation FacebbokViewController
- (id)init
{
self = [super init];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// button which I have used
UIButton *login=[[UIButton alloc]initWithFrame:CGRectMake(100,100, 200,80)];
[login setBackgroundColor:[UIColor blueColor]];
[login setTitle:#"login With facebook" forState:UIControlStateNormal];
[login setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[login addTarget:self action:#selector(loginWithFacebook) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:login];
}
// method which excute on my button click
-(IBAction)loginWithFacebook{
UserAppAppDelegate *appDelegate = [[UIApplication sharedApplication]delegate];
NSArray *permissions = [[NSArray alloc] initWithObjects:
#"email", nil];
if(!appDelegate.session.isOpen)
{
// create a fresh session object
appDelegate.session = [[FBSession alloc] init];
[FBSession setActiveSession: appDelegate.session];
[FBSession openActiveSessionWithReadPermissions:permissions
allowLoginUI:YES
completionHandler:^(FBSession *session, FBSessionState state, NSError *error) {
[self sessionStateChanged:session state:state error:error];
}];
}
else{
NSLog(#"hi");
}
}
- (void)sessionStateChanged:(FBSession *)session state:(FBSessionState) state error:(NSError *)error
{
// If the session was opened successfully
if (!error && state == FBSessionStateOpen){
NSLog(#"Session opened");
[self userData]; // method created to fetch user’s data.
// Show the user the logged-in UI
// do all the things as you have the info you requested from facebook
return;
}
if (state == FBSessionStateClosed || state == FBSessionStateClosedLoginFailed){
// If the session is closed
NSLog(#"Session closed");
// Show the user the logged-out UI
[FBSession.activeSession closeAndClearTokenInformation];
}
// 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];
// Here we will handle all other errors with a generic error message.
// We recommend you check our Handling Errors guide for more information
// https://developers.facebook.com/docs/ios/errors/
} else {
//Get more error information from the error
NSDictionary *errorInformation = [[[error.userInfo objectForKey:#"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: %#", [errorInformation objectForKey:#"message"]];
[self showMessage:alertText withTitle:alertTitle];
}
}
// Clear this token
[FBSession.activeSession closeAndClearTokenInformation];
}
}
-(void)showMessage:(NSString*)alertMessage withTitle:(NSString*)alertTitle
{
[[[UIAlertView alloc] initWithTitle:alertTitle
message:alertMessage
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil] show];
}
-(void)userData
{
// Start the facebook request
[FBRequestConnection startWithGraphPath:#"me" parameters:[NSDictionary dictionaryWithObject:#"id,email" forKey:#"fields"] HTTPMethod:#"GET" completionHandler:^(FBRequestConnection *connection, NSDictionary<FBGraphUser> *result, NSError *error)
{
//if(!error){
// NSLog(#"result %#",result);
NSString *fbid =result[#"email"];
NSLog(#"result %#",fbid);
//}
}];
}
you can use FBLoginView to have the the functionality as your requirement , you can use like this
FBLoginView *loginView = [[FBLoginView alloc] init];
loginView.frame = YOURFRAME;
[self.view addSubview:loginView];
Take a look at FBLoginView in the Facebook SDK. Official link/tutorial. In the later part of the tutorial, implementing custom views and logging in with API calls is also covered. But note that you would have to design your button on your own in the latter case.

iOS Facebook login doesn't work

I have an app, for iOS5 and above, in which I am trying to set up Facebook login. All works fine when there is a Facebook account integrated in the phone. If it is not, it doesn't work. This is even if the Facebook app is installed.
When the app is installed, it opens the app, asks me permission to access the appropriate user data and returns to my app with no result. It the same when it isn't installed. Safari is opened, asks me for authorization, returns, and nothing.
I followed all the steps mentioned in the Facebook Login tutorial. Is this a problem only I am facing?
EDIT: This is the requested code:
I open a session like so:
- (BOOL)openSessionWithAllowLoginUI:(BOOL)allowLoginUI {
NSArray *permissions = [[NSArray alloc] initWithObjects:
#"email",
nil];
return [FBSession openActiveSessionWithReadPermissions:permissions
allowLoginUI:allowLoginUI
completionHandler:^(FBSession *session,
FBSessionState state,
NSError *error) {
[self sessionStateChanged:session
state:state
error:error];
}];
}
And when it returns, I guess this method must be called. but it isn't:
- (void)sessionStateChanged:(FBSession *)session
state:(FBSessionState) state
error:(NSError *)error
{
switch (state) {
case FBSessionStateOpen:
if (!error) {
// We have a valid session
NSLog(#"session opened");
FBRequest *me = [FBRequest requestForMe];
__block NSString *username = nil;
[me startWithCompletionHandler:^(FBRequestConnection *connection,
id result,
NSError *error) {
NSDictionary<FBGraphUser> *my = (NSDictionary<FBGraphUser> *) result;
// NSLog(#"User session found: %#", my.username);
username = my.username;
}];
// /fb_access/:access_token
}
break;
case FBSessionStateClosed:
if (!error) {
// We have a valid session
NSLog(#"User session closed");
}
case FBSessionStateClosedLoginFailed:
NSLog(#"login failed, %#", error);
[FBSession.activeSession closeAndClearTokenInformation];
break;
default:
break;
}
[[NSNotificationCenter defaultCenter]
postNotificationName:FBSessionStateChangedNotification
object:session];
if (error) {
UIAlertView *alertView = [[UIAlertView alloc]
initWithTitle:#"Error"
message:error.localizedDescription
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];
}
}
Any ideas?
add below key-value pair in your plist.
Add Field (key) FacebookAppID - (value) fbID
Add Field - URL Types (key)
Add 2 Field in URL Types:
(key) URL Identifier - (value) (i.e. YourApplication name)
(key)-URL Schemes
Add Field in URL Schemes (key) - (value) fb(fbID) (e.g. fb557354324264278)
Add following method in to your appdelgate
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{ // attempt to extract a token from the url return
[FBSession.activeSession handleOpenURL:url];
}
Both answers by iUser and Kalpesh are right. Combining both of them worked for me. Please refer to them. :)

Log out from facebook like in native app

My application supports login with facebook, but when I log out and log in again I am not asked for any credentials - it immediately logs in with the username which goes native in iOS6. I want something like in native facebook application:
When clicking "not you" facebook offers new login screen.
I followed this tutorial
The problem seems to be somewhere here:
- (void)openSession
{
NSArray *permissions=[NSArray arrayWithObjects: #"publish_stream", #"publish_actions",#"create_event", nil];
// [FBSession open]
[FBSession openActiveSessionWithPublishPermissions:permissions
defaultAudience:FBSessionDefaultAudienceEveryone
allowLoginUI:YES
completionHandler:
^(FBSession *session,
FBSessionState state, NSError *error) {
[self sessionStateChanged:session state:state error:error];
}];
}
- (void)sessionStateChanged:(FBSession *)session
state:(FBSessionState) state
error:(NSError *)error
{
switch (state) {
case FBSessionStateOpen: {
NSLog(#"Sesstion opened");
UIViewController *topViewController =
[self.navController topViewController];
NSLog(#"Class: %#", [[topViewController presentedViewController] class]);
if ([[topViewController presentedViewController]
isKindOfClass:[LoginViewController class]])
{
[topViewController dismissViewControllerAnimated:YES completion:nil];
}
ViewController *basic=(ViewController*)topViewController;
NSLog(#"Populating details");
[basic populateUserDetails];
}
break;
case FBSessionStateClosed:
{
NSLog(#"Session closed");
[FBSession.activeSession closeAndClearTokenInformation];
}
case FBSessionStateClosedLoginFailed:
NSLog(#"Login failed");
[self.navController popToRootViewControllerAnimated:NO];
[FBSession.activeSession closeAndClearTokenInformation];
[self showLoginView];
break;
default:
break;
}
if (error) {
UIAlertView *alertView = [[UIAlertView alloc]
initWithTitle:#"Error"
message:error.localizedDescription
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];
}
}
I am not sure the Facebook SDK supports that - although I might be wrong. The idea (as I understand it) is that Facebook login allows the currently logged in Facebook user to login to your app. If no one is logged in to Facebook, the credentials page will be shown. After providing valid credentials, the user will be logged in to Facebook and an auth_token is sent to your app.
The point is that you can't authenticate a different user than the one currently logged in to Facebook. That would first require a logout of the current user and I think Facebook wish to keep this "change user" functionality to the Facebook app.
Also, note that when logging out from your app, the user stays logged in to Facebook. This is different from the policy that applies to web sites that use Facebook authentication. In that case, the user should be logged out both from the site and from Facebook.

Facebook log in error 400

I am logging in into facebook in this way:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[FBSession openActiveSessionWithReadPermissions:nil
allowLoginUI:YES
completionHandler:
^(FBSession *session,
FBSessionState state, NSError *error) {
[self sessionStateChanged:session state:state error:error];
}];
return YES;
}
- (void)sessionStateChanged:(FBSession *)session
state:(FBSessionState) state
error:(NSError *)error
{
switch (state) {
case FBSessionStateOpen:
if (!error) {
// We have a valid session
//NSLog(#"User session found");
// Initiate a Facebook instance
self.facebook = [[Facebook alloc]
initWithAppId:FBSession.activeSession.appID
andDelegate:nil];
// Store the Facebook session information
self.facebook.accessToken = FBSession.activeSession.accessToken;
self.facebook.expirationDate = FBSession.activeSession.expirationDate;
}
break;
case FBSessionStateClosed:
case FBSessionStateClosedLoginFailed:
[FBSession.activeSession closeAndClearTokenInformation];
// Clear out the Facebook instance
self.facebook = nil;
break;
default:
break;
}
if (error) {
UIAlertView *alertView = [[UIAlertView alloc]
initWithTitle:#"Error"
message:error.localizedDescription
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];
}
}
- (BOOL)application:(UIApplication *)application
openURL:(NSURL *)url
sourceApplication:(NSString *)sourceApplication
annotation:(id)annotation {
// attempt to extract a token from the url
self.openedURL = url;
// attempt to extract a token from the url
return [FBSession.activeSession handleOpenURL:url];
}
...and I get the error: Error: HTTP status code: 400
I have set up the URL scheme in the plist. Why am I getting this?
Check in the App Dashboard. Look at your Basic Settings. Your Sandbox Mode may be set to Enabled. The errors should go away when your app is out of Sandbox mode.

Post an image on my own Facebook wall with Facebook SDK 3.0 (beta), Xcode 4.3.2

I am using Facebook SDK 3.0 (with Xcode 4.3.2 also and with ARC disabled), I already wrote the codes for login and post a text message on my own Facebook wall (codes above), everything run perfectly :
- (IBAction)loginFacebook:(id)sender {
// Initiate a Facebook instance
Facebook *facebook = [[Facebook alloc] initWithAppId:#"My_App_ID" andDelegate:nil];
// Set the session information for the Facebook instance
facebook.accessToken = self.session.accessToken;
facebook.expirationDate = self.session.expirationDate;
// Put together the dialog parameters
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
#"I'm using Emoji-Smileys", #"name",
#"Facebook for iOS", #"caption",
#"Check out the application Emoji-Smileys for iOS to enable emoji keyboard, and make fun messages! There are 460 smileys!", #"description",
#"http://m.facebook.com/apps/hackbookios/", #"link",
#"http://a365.phobos.apple.com/us/r30/Purple/v4/fa/96/4c/fa964c2a-3a48-4f6d-7789-d3105a392a9f/mzl.evuvwyjk.png?downloadKey=1343552764_471c078e9d07fde2b00bd3f1ee1d88a7", #"picture",
nil];
// Invoke the dialog
[facebook dialog:#"feed" andParams:params andDelegate:self];
}
- (FBSession *)createNewSession
{
self.session = [[FBSession alloc] init];
return self.session;
}
- (void)sessionStateChanged:(FBSession *)session
state:(FBSessionState) state
error:(NSError *)error
{
switch (state) {
case FBSessionStateOpen:
if (!error) {
// We have a valid session
NSLog(#"User session found");
}
break;
case FBSessionStateClosed:
case FBSessionStateClosedLoginFailed:
[session closeAndClearTokenInformation];
self.session = nil;
[self createNewSession];
break;
default:
break;
}
if (error) {
UIAlertView *errorAlert = [[UIAlertView alloc]
initWithTitle:#"Error"
message:error.localizedDescription
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[errorAlert show];
}
}
- (void) openSession {
[self.session openWithCompletionHandler:
^(FBSession *session, FBSessionState state, NSError *error) {
[self sessionStateChanged:session state:state error:error];
}];
}
- (BOOL)application:(UIApplication *)application
openURL:(NSURL *)url
sourceApplication:(NSString *)sourceApplication
annotation:(id)annotation
{
return [self.session handleOpenURL:url];
}
Okay, now, I'd like to know how to post an image that I give in my application, no need to use the UIImagePickerViewController, I don't want to select the image. I don't know if I need a publish_stream, read_stream or user_likes permission or other thing.
Thanks in advance for your help.
Cheers.
You can use this code, which helped me:
[FBRequestConnection startForUploadPhoto:myImg.image
completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if (!error) {
// is success do something...
} else {
// If some error , do something...
}
}];
myImg is your image which you can replace with:
[UIImage imageNamed:#"image.jpg"]
I bet these tutorials will help you a lot:
http://www.raywenderlich.com/1488/how-to-use-facebooks-new-graph-api-from-your-iphone-app
http://www.raywenderlich.com/1578/how-to-get-a-user-profile-with-facebooks-new-graph-api-from-your-iphone-app
http://www.raywenderlich.com/1626/how-to-post-to-a-users-wall-upload-photos-and-add-a-like-button-from-your-iphone-app
And bookmark this site, it has a lot of great tutorials!)

Resources