Integrating Facebook SDK for older versions of Xcode to Support both iOS 5 and iOS 6 - iphone

I am still using XCode 4.3.2 and iOS 5.1 base SDK. What I want to achieve is to integrate Facebook API for iOS 5.0+ devices. Just basic features such as posting on behalf and getting basic user information.
I am assuming that which ever Facebook SDK works on iOS 5, will work on iOS 6, but I am not sure about that.
As a rookie on Facebook Integration, can anybody shed some light on this issue. ( Since I am working on the project, upgrading the XCode and the iOS SDK is not an option)
Which iOS SDK should I be looking into?
Can I support both iOS 5 and
6, with base SDK 5.1 and XCode 4.3?
Is there an API supporting both iOS versions?
Any musts for Facebook Integration?

First of all you read this article published from Facebook developers
http://developers.facebook.com/docs/getting-started/facebook-sdk-for-ios/
in step 1 it will also work for xcode 4.3
you carefully read all steps one by one n implement
In step6 you write code as follow on where Facebook Btn Pressed
- (IBAction)facebookBtnPressed:(id)sender
{
// if it is available to us, we will post using the native dialog
BOOL displayedNativeDialog = [FBNativeDialogs presentShareDialogModallyFrom:self
initialText:[NSString stringWithFormat:#"Here U write code which u want to post on facebook"]
image:[UIImage imageNamed:#"1.jpg"]
url:[NSURL URLWithString:#""]
handler:nil];
if (!displayedNativeDialog)
{
NSString *shareStr = [NSString stringWithFormat:#"Here U write code which u want to post on facebook"];
NSMutableDictionary* params = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
shareStr,#"description",
#"sharelink", #"link",
#"ImageName", #"picture",
nil];
[self performPublishAction:^{
[FBRequestConnection startWithGraphPath:#"me/feed" parameters:params HTTPMethod:#"POST" completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if (error)
{
NSLog(#"error in post");
}
else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Success" message:#"Post Successfully" delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alert show];
}
}];
}];
}
//}
//===set delagate in Viewcontroller.h of mySLComposerSheet
[mySLComposerSheet setCompletionHandler:^(SLComposeViewControllerResult result) {
NSString *output;
switch (result) {
case SLComposeViewControllerResultCancelled:
output = #"Action Cancelled";
break;
case SLComposeViewControllerResultDone:
output = #"Post Successfully";
break;
default:
break;
} //check if everything worked properly. Give out a message on the state.
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Facebook" message:output delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alert show];
}];
}
- (void) performPublishAction:(void (^)(void)) action {
if ([[FBSession activeSession]isOpen]) {
/*
* if the current session has no publish permission we need to reauthorize
*/
if ([[[FBSession activeSession]permissions]indexOfObject:#"publish_actions"] == NSNotFound) {
[[FBSession activeSession] reauthorizeWithPublishPermissions:[NSArray arrayWithObject:#"publish_actions"]
defaultAudience:FBSessionDefaultAudienceOnlyMe
completionHandler:^(FBSession *session, NSError *error) {
action();
}];
}else{
action();
}
}else{
/*
* open a new session with publish permission
*/
[FBSession openActiveSessionWithPublishPermissions:[NSArray arrayWithObject:#"publish_actions"]
defaultAudience:FBSessionDefaultAudienceOnlyMe
allowLoginUI:YES
completionHandler:^(FBSession *session, FBSessionState status, NSError *error) {
if (!error && status == FBSessionStateOpen) {
action();
}else{
NSLog(#"error");
}
}];
}
}

Related

FBWebDialogs presentRequestsDialogModallyWithSession is not working?

This code is not generating notification on friend's end.But sending successully generating no error.I am building a app for Game url on friend to invite them to play.i have written below code to send url.it's working fine and not generating no error but user is not getting any request for App.
//Fbwebdialog generating no error
[FBWebDialogs presentRequestsDialogModallyWithSession:[FBSession activeSession]
message:[NSString stringWithFormat:#"I just smashed friends! Can you beat it?"]
title:nil
parameters:params
handler:^(FBWebDialogResult result, NSURL *resultURL, NSError *error) {
if (error) {
// Case A: Error launching the dialog or sending request.
NSLog(#"Some errorr: %#", [error description]);
UIAlertView *alrt = [[UIAlertView alloc] initWithTitle:#"Invitiation Sending Failed" message:#"Unable to send inviation at this Moment, please make sure your are connected with internet" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alrt show];
} else {
if (![resultURL query]) {
return ;
NSLog(#"User canceled request.");
} else {
NSDictionary *params = [self parseURLParams:[resultURL query]];
NSMutableArray *recipientIDs = [[NSMutableArray alloc] init];
for (NSString *paramKey in params){
if ([paramKey hasPrefix:#"to["]){
[recipientIDs addObject:[params objectForKey:paramKey]];
}
}
if ([params objectForKey:#"request"]){
NSLog(#"Request ID: %#", [params objectForKey:#"request"]);
NSArray *requestIDs=[params objectForKey:#"request"];
}
if ([recipientIDs count] > 0){
//[self showMessage:#"Sent request successfully."];
//NSLog(#"Recipient ID(s): %#", recipientIDs);
// punGameViewController *pun=[[punGameViewController alloc]initWithNibName:#"punGameViewController" bundle:nil];
UIAlertView *alrt = [[UIAlertView alloc] initWithTitle:#"Success!" message:#"Successfully send" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alrt show];
// [self.navigationController pushViewController:pun animated:YES];
}
}
}
}];
//end of code here
check it find the reason not generating notification.
I found my answer to this question on a previously answered S/O question. Basically, you need to set the App Store Id and Bundle Id in the Facebook App settings in order for invites to get sent. You can find that info: here
Notifications sent by your app is only received on mobile devices if your app is a game. If your app is not a game, notifications are still delivered to the App Center on the desktop.

Does not receive any "Request" after sending out from iOS Facebook SDK

I'm following these two tutorials in Facebook developer website
https://developers.facebook.com/docs/tutorials/ios-sdk-games/requests/
https://developers.facebook.com/docs/howtos/send-requests-using-ios-sdk/#step2
These are my codes:
[FBWebDialogs presentRequestsDialogModallyWithSession:nil
message:[NSString stringWithFormat:#"I just smashed %u friends! Can you beat it?", score]
title: nil
parameters:params
handler:^(FBWebDialogResult result, NSURL *resultURL, NSError *error)
{
if (error)
{
// Case A: Error launching the dialog or sending request.
UIAlertView* alert = [[UIAlertView alloc] initWithTitle: #"Facebook" message: error.description delegate: nil cancelButtonTitle: #"Ok" otherButtonTitles: nil];
[alert show];
[alert release];
}
else
{
if (result == (FBWebDialogResultDialogCompleted))
{
// Handle the publish feed callback
NSDictionary *urlParams = [self parseURLParams:[resultURL query]];
if ([urlParams valueForKey: #"request"])
{
// User clicked the Share button
NSLog(#"Send");
}
}
}
}];
Problem is after I send out the request, my friend told me that he doesn't receive any notification/request in FB Notification Center site. Does anyone know why?
These are the things I've done:
I've setup properly in info.plist and the Facebook App.
I'm not using Sandbox mode.
My current application is able to log in and post to wall.
I've publish_actions permission.
I did not received any error or warning.
I found my solution here:
Facebook App Requests aren't shown on iOS devices?
It is because I didn't set the iPhone App ID and iPad App ID
Use following method, it will help you :
-(void)openFacebookAuthentication
{
NSArray *permission = [NSArray arrayWithObjects:kFBEmailPermission,kFBUserPhotosPermission, nil];
FBSession *session = [[FBSession alloc] initWithPermissions:permission];
[FBSession setActiveSession: [[FBSession alloc] initWithPermissions:permission] ];
[[FBSession activeSession] openWithBehavior:FBSessionLoginBehaviorForcingWebView completionHandler:^(FBSession *session, FBSessionState status, NSError *error) {
switch (status) {
case FBSessionStateOpen:
[self getMyData];
break;
case FBSessionStateClosedLoginFailed: {
// prefer to keep decls near to their use
// unpack the error code and reason in order to compute cancel bool
NSString *errorCode = [[error userInfo] objectForKey:FBErrorLoginFailedOriginalErrorCode];
NSString *errorReason = [[error userInfo] objectForKey:FBErrorLoginFailedReason];
BOOL userDidCancel = !errorCode && (!errorReason || [errorReason isEqualToString:FBErrorLoginFailedReasonInlineCancelledValue]);
//Added by Rigel Networks July 2, 2013 to solve Facebook Cancel button popup issue
if(error.code == 2 && ![errorReason isEqualToString:#"com.facebook.sdk:UserLoginCancelled"]) {
UIAlertView *errorMessage = [[UIAlertView alloc] initWithTitle:kFBAlertTitle
message:kFBAuthenticationErrorMessage
delegate:nil
cancelButtonTitle:kOk
otherButtonTitles:nil];
[errorMessage performSelectorOnMainThread:#selector(show) withObject:nil waitUntilDone:YES];
errorMessage = nil;
}
}
break;
// presently extension, log-out and invalidation are being implemented in the Facebook class
default:
break; // so we do nothing in response to those state transitions
}
}];
permission = nil;
}

How to post to a users wall using Facebook SDK

I want to post some text to a users wall using the facebook sdk in an iOS app.
Is posting an open graph story now the only way to do that?
I've found with open graph stories they are really strange, you can only post things in the format "user x a y" where you preset x and y directly on facebook, like user ata a pizza or user played a game. Setting up each one is pretty laborious too because you have to create a .php object on an external server for each one.
Am I missing something or is there a simpler way to go about this?
Figured it out by browsing the facebook tutorials a bit more.
-(void) postWithText: (NSString*) message
ImageName: (NSString*) image
URL: (NSString*) url
Caption: (NSString*) caption
Name: (NSString*) name
andDescription: (NSString*) description
{
NSMutableDictionary* params = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
url, #"link",
name, #"name",
caption, #"caption",
description, #"description",
message, #"message",
UIImagePNGRepresentation([UIImage imageNamed: image]), #"picture",
nil];
if ([FBSession.activeSession.permissions indexOfObject:#"publish_actions"] == NSNotFound)
{
// No permissions found in session, ask for it
[FBSession.activeSession requestNewPublishPermissions: [NSArray arrayWithObject:#"publish_actions"]
defaultAudience: FBSessionDefaultAudienceFriends
completionHandler: ^(FBSession *session, NSError *error)
{
if (!error)
{
// If permissions granted and not already posting then publish the story
if (!m_postingInProgress)
{
[self postToWall: params];
}
}
}];
}
else
{
// If permissions present and not already posting then publish the story
if (!m_postingInProgress)
{
[self postToWall: params];
}
}
}
-(void) postToWall: (NSMutableDictionary*) params
{
m_postingInProgress = YES; //for not allowing multiple hits
[FBRequestConnection startWithGraphPath:#"me/feed"
parameters:params
HTTPMethod:#"POST"
completionHandler:^(FBRequestConnection *connection,
id result,
NSError *error)
{
if (error)
{
//showing an alert for failure
UIAlertView *alertView = [[UIAlertView alloc]
initWithTitle:#"Post Failed"
message:error.localizedDescription
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];
}
m_postingInProgress = NO;
}];
}
the easiest way of sharing something from your iOS app is using the UIActivityViewController class, here you can find the documentation of the class and here a good example of use. It is as simple as:
NSString *textToShare = #”I just shared this from my App”;
UIImage *imageToShare = [UIImage imageNamed:#"Image.png"];
NSURL *urlToShare = [NSURL URLWithString:#"http://www.bronron.com"];
NSArray *activityItems = #[textToShare, imageToShare, urlToShare];
UIActivityViewController *activityVC = [[UIActivityViewController alloc]initWithActivityItems:activityItems applicationActivities:nil];
[self presentViewController:activityVC animated:TRUE completion:nil];
This will only work on iOS 6 and it makes use of the Facebook account configured in the user settings, and the Facebook SDK is not needed.
You can use Graph API as well.
After all the basic steps to create facebook app with iOS, you can start to enjoy the functionality of Graph API. The code below will post "hello world!" on your wall:
#import <FBSDKCoreKit/FBSDKCoreKit.h>
#import <FBSDKLoginKit/FBSDKLoginKit.h>
...
//to get the permission
//https://developers.facebook.com/docs/facebook-login/ios/permissions
if ([[FBSDKAccessToken currentAccessToken] hasGranted:#"publish_actions"]) {
NSLog(#"publish_actions is already granted.");
} else {
FBSDKLoginManager *loginManager = [[FBSDKLoginManager alloc] init];
[loginManager logInWithPublishPermissions:#[#"publish_actions"] handler:^(FBSDKLoginManagerLoginResult *result, NSError *error) {
//TODO: process error or result.
}];
}
if ([[FBSDKAccessToken currentAccessToken] hasGranted:#"publish_actions"]) {
[[[FBSDKGraphRequest alloc]
initWithGraphPath:#"me/feed"
parameters: #{ #"message" : #"hello world!"}
HTTPMethod:#"POST"]
startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
if (!error) {
NSLog(#"Post id:%#", result[#"id"]);
}
}];
}
...
The basic staff is presented here: https://developers.facebook.com/docs/ios/graph
The explorer to play around is here:
https://developers.facebook.com/tools/explorer
A good intro about it: https://www.youtube.com/watch?v=WteK95AppF4

Get publish permission for Facebook app for iOS with -openWithBehavior:completionHandler:

In my application I need user to sign in to Facebook, get friend list in my table view and Post on feeds, but I don't want to redirect the user anywhere. so I used -openWithBehavior:completionHandler: ... Here is my code.
-(IBAction)loginAction:(id)sender {
[self deleteCookies];
// get the app delegate so that we can access the session property
DLAppDelegate *appDelegate = [[UIApplication sharedApplication]delegate];
// this button's job is to flip-flop the session from open to closed
if (appDelegate.session.isOpen) {
// if a user logs out explicitly, we delete any cached token information, and next
// time they run the applicaiton they will be presented with log in UX again; most
// users will simply close the app or switch away, without logging out; this will
// cause the implicit cached-token login to occur on next launch of the application
[appDelegate.session closeAndClearTokenInformation];
} else {
if (appDelegate.session.state != FBSessionStateCreated) {
// Create a new, logged out session.
appDelegate.session = [[FBSession alloc] init];
[self updateView];
}
// if the session isn't open, let's open it now and present the login UX to the user
[appDelegate.session openWithBehavior:FBSessionLoginBehaviorForcingWebView completionHandler:^(FBSession *session, FBSessionState status, NSError *error) {
switch (status) {
case FBSessionStateOpen:
// call the legacy session delegate
//Now the session is open do corresponding UI changes
{
FBCacheDescriptor *cacheDescriptor = [FBFriendPickerViewController cacheDescriptor];
[cacheDescriptor prefetchAndCacheForSession:session];
[FBSession openActiveSessionWithAllowLoginUI:NO];
[FBSession openActiveSessionWithPublishPermissions:[NSArray arrayWithObjects:#"publish_stream",#"publish_actions", nil] defaultAudience:FBSessionDefaultAudienceFriends allowLoginUI:NO completionHandler:nil];
}
break;
case FBSessionStateClosedLoginFailed:
{ // prefer to keep decls near to their use
// unpack the error code and reason in order to compute cancel bool
// call the legacy session delegate if needed
//[[delegate facebook] fbDialogNotLogin:userDidCancel];
}
break;
// presently extension, log-out and invalidation are being implemented in the Facebook class
default:
break; // so we do nothing in response to those state transitions
}
[self updateView];
}];
}
}
The user is successfully signed in and I can retrieve the friend list by using FQL. The problem is while posting to feeds. I know I need to get publish permissions to do it. But when I uses the following code to post...
- (IBAction)postAction:(id)sender {
DLAppDelegate *appDelegate = [[UIApplication sharedApplication]delegate];
if (appDelegate.session.isOpen) {
[FBSession openActiveSessionWithAllowLoginUI:NO];
NSMutableDictionary *postParams = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
#"https://developers.facebook.com/ios", #"link",
#"https://developers.facebook.com/attachment/iossdk_logo.png", #"picture",
#"Facebook SDK for iOS", #"name",
#"Build great social apps and get more installs.", #"caption",
#"The Facebook SDK for iOS makes it easier and faster to develop Facebook integrated iOS apps.", #"description",
nil];
if ([_postText.text length]>0) {
[postParams setObject:[_postText text] forKey:#"message"];
}
if (([FBSession.activeSession.permissions
indexOfObject:#"publish_actions"] == NSNotFound) ||
([FBSession.activeSession.permissions
indexOfObject:#"publish_stream"] == NSNotFound)) {
// No permissions found in session, ask for it
[FBSession.activeSession
reauthorizeWithPublishPermissions:
[NSArray arrayWithObjects:#"publish_stream",#"publish_actions",nil]
defaultAudience:FBSessionDefaultAudienceFriends
completionHandler:^(FBSession *session, NSError *error) {
if (!error) {
// If permissions granted, publish the story
[self publishStory:postParams];
}
}];
} else {
// If permissions present, publish the story
[self publishStory:postParams];
}
}
}
-(void)publishStory:(NSDictionary *)postParams {
[FBRequestConnection startWithGraphPath:
#"me/feed" parameters:postParams HTTPMethod:#"POST"
completionHandler:^(FBRequestConnection *connection, id result, NSError *error)
{
if (!error) {
//Tell the user that it worked.
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Shared:"
message:[NSString stringWithFormat:#"Sucessfully posted to your wall."]
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
alertView.tag = 101;
[alertView show];
}
else {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error:"
message:error.localizedDescription
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];
NSLog(#"%#",error);
}
}
];
}
This code redirects the user to Safari or Facebook App. Which I don't want to happen.
Definitely I need to get publish permissions while logging in. the question is HOW?
You have to set FBSessionLoginBehavior, to change it the only way is to use:
[session openWithBehavior:FBSessionLoginBehaviorWithNoFallbackToWebView
completionHandler:^(FBSession *session,
FBSessionState status,
NSError *error) {
// Respond to session state changes,
// ex: updating the view
}];
I see you use FBSessionLoginBehaviorForcingWebView, so to get what you want you have to choose from this enum:
typedef enum {
/*! Attempt Facebook Login, ask user for credentials if necessary */
FBSessionLoginBehaviorWithFallbackToWebView = 0,
/*! Attempt Facebook Login, no direct request for credentials will be made */
FBSessionLoginBehaviorWithNoFallbackToWebView = 1,
/*! Only attempt WebView Login; ask user for credentials */
FBSessionLoginBehaviorForcingWebView = 2,
/*! Attempt Facebook Login, prefering system account and falling back to fast app switch if necessary */
FBSessionLoginBehaviorUseSystemAccountIfPresent = 3,
} FBSessionLoginBehavior;
Now to solve this "Definitely I need to get publish permissions while logging in. the question is HOW?" you may - (id)initWithPermissions:(NSArray*)permissions; your Session :
NSArray *permissions = #[#"publish_stream", #"publish_actions"];
appDelegate.session = [[FBSession alloc] initWithPermissions:permissions];

Integration error while posting message on friends wall?

i m using facebook_skd_3.1 (Xcode ios 4.5) i got the friends list by calling
FBFriendPickerViewController, on clicking done button i have tried to post the message
on the selected friends wall but i got this error :-
Warning: Attempt to dismiss from view controller
while a presentation or dismiss is in progress!
2012-12-06 19:37:09.187 ........project[5474:19a03] Error: HTTP status code: 403
error in the alert view
error =Error Domain=com.facebook.sdk code=5" ..........
message = "(#200)the user hasn't authorized the application to perform this action";
type = OAuthException
};
};
code=403;
com.acebook.sdk:HTTPStatuscode=403}
code :-
-(void)facebookViewControllerDoneWasPressed:(id)sender {
NSString* userid;
for (id<FBGraphUser> user in self.friendPickerController.selection)
{
NSLog(#"\nuser=%#\n", user);
userid = user.id;
}
NSMutableDictionary* dictaram = [[NSMutableDictionary alloc]
initWithObjectsAndKeys:#"like this!", #"message", nil];
[FBRequestConnection startWithGraphPath:[NSString stringWithFormat:#"%#/feed", userid]
parameters:params HTTPMethod:#"POST"
completionHandler:^(FBRequestConnection *connection, id result, NSError *error)
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Shared"
message:[NSString stringWithFormat:# %#! error=%#", fbUserName, error]
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];
}
];
[self dismissModalViewControllerAnimated:YES];
Do i need some permissions or there is some coding error please help.
thanks in advance.
Please dismiss viewcontroller after some delay.
I have figured it by re authorizing the permissions as follows in delegate i have read permissions for session so that didn't worked for posting. write the following code to in the ButtonAction and you will get the proper output.
NSArray *permissions =[NSArray arrayWithObjects:#"publish_actions",#"publish_stream",#"manage_friendlists", nil];
[[FBSession activeSession] reauthorizeWithPublishPermissions:permissions defaultAudience:FBSessionDefaultAudienceFriends
completionHandler:^(FBSession *session, NSError *error) {
/* handle success + failure in block */
}];