Facebook SDK 3.5 is not working on ios 5.1 - iphone

I have implemented facebook in my application. It is working on ios 6 but when it os run on ios5 it is giving error as " The operation coudn't be completed (com.facebook.sdk error 2)"
Following is my code
- (void)postStatusUpdateClick:(NSString *)url:(UIViewController*)view:(UIView*)view1
{
NSString *shareString=[NSString stringWithFormat:#"Check out this great deal at %#",url];
NSURL *urlToShare = [NSURL URLWithString:url];
FBAppCall *appCall = [FBDialogs presentShareDialogWithLink:urlToShare
name:#"Hello Facebook"
caption:nil
description:shareString
picture:nil
clientState:nil
handler:^(FBAppCall *call, NSDictionary *results, NSError *error) {
if (error) {
NSLog(#"Error: %#", error.description);
} else {
NSLog(#"Success!");
}
}];
if (!appCall) {
// Next try to post using Facebook's iOS6 integration
BOOL displayedNativeDialog = [FBDialogs presentOSIntegratedShareDialogModallyFrom:view
initialText:shareString
image:nil
url:urlToShare
handler:^(FBOSIntegratedShareDialogResult result, NSError *error) {
if (error && [error code] == 7) {
return;
} NSString *alertText = #"";
if (error) {
alertText = [NSString stringWithFormat:
#"error: domain = %#, code = %d",
error.domain, error.code];
} else if (result == FBNativeDialogResultSucceeded) {
alertText = #"Posted successfully.";
}
if (![alertText isEqualToString:#""]) {
// Show the result in an alert
[[[UIAlertView alloc] initWithTitle:#"Result"
message:alertText
delegate:self
cancelButtonTitle:#"OK!"
otherButtonTitles:nil]
show];
}
}];
if (!displayedNativeDialog) {
// Lastly, fall back on a request for permissions and a direct post using the Graph API
[self performPublishAction:^{
[FBRequestConnection startForPostStatusUpdate:shareString
completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
[self showAlert:#"jhj" result:result error:error];
}];
}];
}
}
}
- (void)showAlert:(NSString *)message
result:(id)result
error:(NSError *)error {
NSString *alertMsg;
NSString *alertTitle;
if (error) {
alertTitle = #"Error";
if (error.fberrorShouldNotifyUser ||
error.fberrorCategory == FBErrorCategoryPermissions ||
error.fberrorCategory == FBErrorCategoryAuthenticationReopenSession) {
alertMsg = error.fberrorUserMessage;
} else {
alertMsg = #"Operation failed due to a connection problem, retry later.";
}
} else {
NSDictionary *resultDict = (NSDictionary *)result;
alertMsg = [NSString stringWithFormat:#"Successfully posted '%#'.", message];
NSString *postId = [resultDict valueForKey:#"id"];
if (!postId) {
postId = [resultDict valueForKey:#"postId"];
}
if (postId) {
alertMsg = [NSString stringWithFormat:#"%#\nPost ID: %#", alertMsg, postId];
}
alertTitle = #"Success";
}
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:alertTitle
message:alertMsg
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView 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] requestNewPublishPermissions:[NSArray arrayWithObject:#"publish_action"] defaultAudience:FBSessionDefaultAudienceFriends
completionHandler:^(FBSession *session,NSError *error){
if (!error) {
action();
}
}];
}else{
//[self publishStory];
action();
}
}else{
/*
* open a new session with publish permission
*/
[FBSession openActiveSessionWithPublishPermissions:[NSArray arrayWithObject:#"publish_actions"]
defaultAudience:FBSessionDefaultAudienceFriends
allowLoginUI:YES
completionHandler:^(FBSession *session,
FBSessionState status,
NSError *error) {
// if login fails for any reason, we alert
if (error) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error"
message:error.localizedDescription
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
}
}
When I Debugged the code it is showing FBSessionStateClosedLoginFailed

Related

Programmatically share videos on facebook by iOS 6 app?

I am working on a app where I need to share videos on Facebook. When I tried developer.facebook.com for solution I found use the graph api to upload a video in ios . It shares video by graph API. Will the graph API work in iOS 6? Please suggest. Also provide any sample code if you have.
Thanks in advance.
Try with this I used Facebook SDK 3.1 https://developers.facebook.com/ios/
.h file
#import <FacebookSDK/FacebookSDK.h>
extern NSString *const SCSessionStateChangedNotificationCamera;
.m file
NSString *const SCSessionStateChangedNotificationCamera = #"com.facebook.Scrumptious:SCSessionStateChangedNotification";
-(IBAction)btnFacebookShareClick:(id)sender {
if (![self openSessionWithAllowLoginUI:YES]) {
[self showLoginView];
}
}
#pragma mark -
#pragma mark - Facebook Method
- (void) performPublishAction:(void (^)(void)) action {
if ([FBSession.activeSession.permissions indexOfObject:#"publish_actions"] == NSNotFound) {
[FBSession.activeSession reauthorizeWithPublishPermissions:[NSArray arrayWithObject:#"publish_actions"] defaultAudience:FBSessionDefaultAudienceFriends completionHandler:^(FBSession *session, NSError *error) {
if (!error) {
action();
}
}];
}
else {
action();
}
}
#pragma mark -
#pragma mark Facebook Login Code
- (void)showLoginView {
[self dismissViewControllerAnimated:NO completion:nil];
[self performSelector:#selector(showLoginView1) withObject:nil afterDelay:1.5f];
}
- (void)showLoginView1 {
}
- (void)sessionStateChanged:(FBSession *)session state:(FBSessionState)state error:(NSError *)error {
switch (state) {
case FBSessionStateOpen: {
if (self != nil) {
[[FBRequest requestForMe] startWithCompletionHandler: ^(FBRequestConnection *connection, NSDictionary<FBGraphUser> *user, NSError *error) {
if (error) {
//error
}else{
if ([FBSession.activeSession.permissions indexOfObject:#"publish_actions"] == NSNotFound) {
NSArray *permissions = [[NSArray alloc] initWithObjects: #"publish_actions", #"publish_stream", nil];
[FBSession.activeSession reauthorizeWithPublishPermissions:permissions defaultAudience:FBSessionDefaultAudienceFriends completionHandler:^(FBSession *session, NSError *error) {
if (!error) {
[self uploadVideoOnFacebook];
}
else {
NSLog(#"%#",error);
}
}];
}
else {
[self uploadVideoOnFacebook];
}
}
}];
}
FBCacheDescriptor *cacheDescriptor = [FBFriendPickerViewController cacheDescriptor];
[cacheDescriptor prefetchAndCacheForSession:session];
}
break;
case FBSessionStateClosed: {
[self StopSpinner];
UIViewController *topViewController = [self.navigationController topViewController];
UIViewController *modalViewController = [topViewController modalViewController];
if (modalViewController != nil) {
[topViewController dismissViewControllerAnimated:YES completion:nil];
}
//[self.navigationController popToRootViewControllerAnimated:NO];
[FBSession.activeSession closeAndClearTokenInformation];
[self performSelector:#selector(showLoginView) withObject:nil afterDelay:0.5f];
}
break;
case FBSessionStateClosedLoginFailed: {
[self StopSpinner];
[self performSelector:#selector(showLoginView) withObject:nil afterDelay:0.5f];
}
break;
default:
break;
}
[[NSNotificationCenter defaultCenter] postNotificationName:SCSessionStateChangedNotificationCamera object:session];
if (error) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:#"Error: %#", [CameraViewController FBErrorCodeDescription:error.code]] message:error.localizedDescription delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertView show];
[alertView release];
}
}
- (BOOL)openSessionWithAllowLoginUI:(BOOL)allowLoginUI {
NSArray *permissions = [[NSArray alloc] initWithObjects: #"publish_actions", #"publish_stream", nil];
return [FBSession openActiveSessionWithPublishPermissions:permissions defaultAudience:FBSessionDefaultAudienceFriends allowLoginUI:allowLoginUI completionHandler:^(FBSession *session, FBSessionState state, NSError *error) {
if (!error) {
[self sessionStateChanged:session state:state error:error];
}
else {
NSLog(#"%#",error);
}
}];
}
+ (NSString *)FBErrorCodeDescription:(FBErrorCode) code {
switch(code){
case FBErrorInvalid :{
return #"FBErrorInvalid";
}
case FBErrorOperationCancelled:{
return #"FBErrorOperationCancelled";
}
case FBErrorLoginFailedOrCancelled:{
return #"FBErrorLoginFailedOrCancelled";
}
case FBErrorRequestConnectionApi:{
return #"FBErrorRequestConnectionApi";
}case FBErrorProtocolMismatch:{
return #"FBErrorProtocolMismatch";
}
case FBErrorHTTPError:{
return #"FBErrorHTTPError";
}
case FBErrorNonTextMimeTypeReturned:{
return #"FBErrorNonTextMimeTypeReturned";
}
case FBErrorNativeDialog:{
return #"FBErrorNativeDialog";
}
default:
return #"[Unknown]";
}
}
-(void) uploadVideoOnFacebook {
NSURL *pathURL;
NSData *videoData;
pathURL = [NSURL URLWithString:self.strUploadVideoURL];
videoData = [NSData dataWithContentsOfURL:[NSURL URLWithString:self.strUploadVideoURL]];
NSString *strDesc;
strDesc = txtCaption.text;
NSDictionary *videoObject = #{#"title": #"application Name",#"description": strDesc,[pathURL absoluteString]: videoData};
FBRequest *uploadRequest = [FBRequest requestWithGraphPath:#"me/videos" parameters:videoObject HTTPMethod:#"POST"];
[self.view setUserInteractionEnabled:NO];
[uploadRequest startWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if (!error)
[AJNotificationView showNoticeInView:self.view type:AJNotificationTypeGreen title:#"Video uploaded successfully" linedBackground:AJLinedBackgroundTypeAnimated hideAfter:3.0];
else
[AJNotificationView showNoticeInView:self.view type:AJNotificationTypeRed title:#"Video uploaded error" linedBackground:AJLinedBackgroundTypeAnimated hideAfter:3.0];
[NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:#selector(popViewAfterMKInfo) userInfo:nil repeats:NO];
}];
}
yes, you can do this, Facebook just has released its new framework 3.5 which will easily work for iOS5 and iOS6 http://developers.facebook.com/ios/

Facebook sdk 3 returns error code 5

I'm using the new facebook SDK... Here I want to post a image from my application to app.
This is the code
NSData* imageData = UIImagePNGRepresentation(emailImage);
NSLog(#"%#",emailImage);
if (xapp.session.isOpen) {
[xapp.session closeAndClearTokenInformation];
} else {
if (xapp.session.state != FBSessionStateCreated) {
// Create a new, logged out session.
xapp.session = [[FBSession alloc] init];
}
[xapp.session openWithCompletionHandler:^(FBSession *session,
FBSessionState status,
NSError *error) {
}];
}
self.postParams =[[NSMutableDictionary alloc] initWithObjectsAndKeys:imageData, #"source",#"My Art", #"message",nil];
// No permissions found in session, ask for it
if ([[FBSession activeSession]isOpen]) {
if ([[[FBSession activeSession]permissions]indexOfObject:#"publish_actions"] == NSNotFound) {
[[FBSession activeSession] reauthorizeWithPublishPermissions:[NSArray arrayWithObjects:#"publish_actions",#"publish_stream",nil]
defaultAudience:FBSessionDefaultAudienceOnlyMe
completionHandler:^(FBSession *session, NSError *error) {
[self publishStory];
}];
}else{
[self publishStory];
}
}else{
NSLog(#"Sessionisclosed");
/
[FBSession openActiveSessionWithPublishPermissions:[NSArray arrayWithObjects:#"publish_stream",#"publish_actions",nil]
defaultAudience:FBSessionDefaultAudienceOnlyMe
allowLoginUI:YES
completionHandler:^(FBSession *session, FBSessionState status, NSError *error) {
if (!error && status == FBSessionStateOpen) {
[FBSession setActiveSession:session];
[self publishStory];
}else{
NSLog(#"error:%d",[error code]);
}
}];
}
- (void)publishStory
{
NSLog(#"PublishStory%#",self.postParams);
[FBRequestConnection
startWithGraphPath:#"me/feed"
parameters:self.postParams
HTTPMethod:#"POST"
completionHandler:^(FBRequestConnection *connection,
id result,
NSError *error) {
NSString *alertText;
if (error) {
alertText = [NSString stringWithFormat:
#"error: domain = %#, code = %d",
error.domain, error.code];
} else {
alertText = [NSString stringWithFormat:
#"Posted action, id: %#",
[result objectForKey:#"id"]];
}
// Show the result in an alert
[[[UIAlertView alloc] initWithTitle:#"Result"
message:alertText
delegate:nil
cancelButtonTitle:#"OK!"
otherButtonTitles:nil]
show];
}];
NSLog(#"PublishStory");
}
Here I'm getting error code 5,which says that there is some permissions problems while posting the image ... But I have used both publish_stream and publish_actions ..I don't know what I'm missing ......
You need to switch to feed dialog because the opengraph is deprecated since feb 2013
refer the link for feeddialog
http://developers.facebook.com/docs/reference/dialogs/feed/

Facebook SDK error 3 and error 2

I have this application I am using for posting on facebook and I am currently facing difficulties in posting on some of the iOS 6.0 devices. I am using facebook SDK 3.1 only and trying to publish action. Following is the code I am using in the class to initiate the read permission.
For the access I am using the following code.
// CALLING THIS CODE BLOCK IN ONE BUTTON ACTION.
if (FBSession.activeSession.isOpen)
{
[self pickaChoice];
}
else
{
[FBSession openActiveSessionWithPublishPermissions:[NSArray arrayWithObjects:#"publish_actions", nil]
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:
[FBSession setActiveSession:session];
[self pickaChoice];
break;
case FBSessionStateClosed:
case FBSessionStateClosedLoginFailed:
// Once the user has logged in, we want them to
// ...
[FBSession.activeSession closeAndClearTokenInformation];
break;
default:
break;
}
if (error) {
NSString* message = [NSString stringWithFormat:#"You have disallowed application to post on your behalf."];
UIAlertView *alertView = [[UIAlertView alloc]
initWithTitle:#"Error"
message:message
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];
[FBSession.activeSession closeAndClearTokenInformation];
}
}
-(void)pickaChoice
{
/* Just a class to select message and then retrieve the message in the next function
-(void)didSelectaPhraseToPost:(NSString *)message */
FBPublishViewController *fbPublishViewController = [[FBPublishViewController alloc] initWithNibName:#"FBPublishViewController"
bundle:[NSBundle mainBundle]];
fbPublishViewController.selectionDelegate = self;
[self presentViewController:fbPublishViewController
animated:YES
completion:^(){
//nil
}];
}
-(void)didSelectaPhraseToPost:(NSString *)message
{
// Selecting a message from a class and retrieving here. This is the message to post on the feed.
[self publishMessage:message];
}
- (void) performPublishAction:(void (^)(void)) action
{
if ([FBSession.activeSession.permissions indexOfObject:#"publish_actions"] == NSNotFound) {
[FBSession.activeSession reauthorizeWithPublishPermissions:[NSArray arrayWithObject:#"publish_actions"]
defaultAudience:FBSessionDefaultAudienceFriends
completionHandler:^(FBSession *session, NSError *error) {
if (!error) {
action();
}
//For this example, ignore errors (such as if user cancels).
}];
} else {
action();
}
}
- (void)publishMessage:(NSString *)message
{
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
#"APP_NAME", #"name",
message, #"message",
APP_LINK, #"link",
#"APP_PICTURE", #"picture",
nil];
[self.spinner startAnimating];
[self performPublishAction:^{
[FBRequestConnection
startWithGraphPath:#"me/feed"
parameters:params
HTTPMethod:#"POST"
completionHandler:^(FBRequestConnection *connection,
id result,
NSError *error) {
[self.spinner stopAnimating];
NSString *messageTitle = nil;
NSString *message = nil;
// If the result came back okay with no errors...
if (result && !error)
{
NSLog(#"accessToken : %#",[FBSession activeSession].accessToken );
NSLog(#"result : %#",result);
messageTitle = #"Success";
message = #"App has posted to facebook";
}else{
NSLog(#"error : %#",error);
messageTitle = #"Error v1.1";
//message = error.localizedDescription;
message = #"Unable to process the request. Please check the permissions for the application.";
[FBSession.activeSession closeAndClearTokenInformation];
}
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:messageTitle
message:message
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles: nil];
[alert show];
//TODO maybe clear connection here if we want to force an new login
}];
}];
}
Now the problem is on some iOS 6.0 devices it is throwing facebook.sdk.error 3 and on some devices it is throwing facebook.sdk.error 2 even when the application is permitted to post. In the current code I have just changed the message to a custom for more user friendly message but if you go on to print the localizedDescription it will show those.
On most of the iOS 6.0 devices the code is working absolutely fine and the message is posted. Let me know if anyone can find out where the problem exactly is. I have spent like days now in this and still not getting where the problem is.
Edit 1
A pattern I observed that when facebook application is installed and user is logged in through it and not logged in through the native settings I am facing these sort of difficulties.
It would be good if you find out your iOS version and use apple's default facebook shar view for iOS 6.0 and on another side for below version you must need to use Graph API.
I used this method its work for me fine in iOS6, may be its help you.
-(void)openFacebookAuthentication
{
NSArray *permission = [NSArray arrayWithObjects:kFBEmailPermission,kFBUserPhotosPermission, nil];
[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: {
NSString *errorCode = [[error userInfo] objectForKey:FBErrorLoginFailedOriginalErrorCode];
NSString *errorReason = [[error userInfo] objectForKey:FBErrorLoginFailedReason];
BOOL userDidCancel = !errorCode && (!errorReason || [errorReason isEqualToString:FBErrorLoginFailedReasonInlineCancelledValue]);
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;
}

Get facebook user details in ios 6 sdk?

How to retrieve facebook user details with ios 6 inbuilt facebook sdk? I tried few examples, but couldn't get work.
- (void) getFBDetails {
if(!_accountStore)
_accountStore = [[ACAccountStore alloc] init];
ACAccountType *facebookTypeAccount = [_accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook];
[_accountStore requestAccessToAccountsWithType:facebookTypeAccount
options:#{ACFacebookAppIdKey: #"514284105262105", ACFacebookPermissionsKey: #[#"email"]}
completion:^(BOOL granted, NSError *error) {
if(granted){
NSArray *accounts = [_accountStore accountsWithAccountType:facebookTypeAccount];
_facebookAccount = [accounts lastObject];
NSLog(#"Success");
[self me];
}else{
// ouch
NSLog(#"Fail");
NSLog(#"Error: %#", error);
}
}];
}
- (void)me{
NSURL *meurl = [NSURL URLWithString:#"https://graph.facebook.com/me"];
SLRequest *merequest = [SLRequest requestForServiceType:SLServiceTypeFacebook
requestMethod:SLRequestMethodGET
URL:meurl
parameters:nil];
merequest.account = _facebookAccount;
[merequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
NSString *meDataString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"%#", meDataString);
}];
}
But this fails to grab data from facebook. My app id is correct.
This the error message I got
Error: Error Domain=com.apple.accounts Code=7 "The Facebook server could not fulfill this access request: no stored remote_app_id for app" UserInfo=0x1d879c90 {NSLocalizedDescription=The Facebook server could not fulfill this access request: no stored remote_app_id for app}
Not sure if this will fix it or not, but have you set the Facebook App ID in your AppName-Info.plist file of your app?
The key required is FacebookAppID, which is of type String.
Try filling in your App ID there as well and see if it works.
In iOS6.0 ,you have to ask read and write permissions separately.
First ask for read permissions that is email then ask for other permissions according to the app requirement.
in .h file
#import <Accounts/Accounts.h>
#import <Social/Social.h>
#property (nonatomic, strong) ACAccountStore *accountStore;
#property (nonatomic, strong) ACAccount *facebookAccount;
in .m file
- (void) getuserdetails
{
self.accountStore = [[ACAccountStore alloc]init];
ACAccountType *FBaccountType= nil;
//[self.accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook];
if (! FBaccountType) {
FBaccountType = [_accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook];
}
NSString *key =kFBAppId;
NSDictionary *dictFB = [NSDictionary dictionaryWithObjectsAndKeys:key,ACFacebookAppIdKey,#[#"email"],ACFacebookPermissionsKey, nil];
[self.accountStore requestAccessToAccountsWithType:FBaccountType options:dictFB completion:
^(BOOL granted, NSError *e)
{
if (granted)
{
NSArray *accounts = [self.accountStore accountsWithAccountType:FBaccountType];
self.facebookAccount = [accounts lastObject];
NSLog(#"facebook account =%#",self.facebookAccount);
[self get];
}
else
{
NSLog(#"fb error %#",e.description);
dispatch_async(dispatch_get_main_queue(), ^
{
[self performSelectorOnMainThread:#selector(hideLoader) withObject:nil waitUntilDone:YES];
NSLog(#"%#",e.description);
if([e code]== ACErrorAccountNotFound)
{
UIAlertView* alt = [[UIAlertView alloc] initWithTitle:#"Account not found"
message:msgSetUpFBAccount delegate:self cancelButtonTitle:nil otherButtonTitles:#"Ok",nil];
[alt show];
}
else
{
UIAlertView* alt = [[UIAlertView alloc] initWithTitle:msgFBAccessDenied
message:#"" delegate:self cancelButtonTitle:nil otherButtonTitles:#"Ok",nil];
[alt show];
}
});
NSLog(#"error getting permission %#",e);
}
}];
}
-(void)get
{
NSURL *requestURL = [NSURL URLWithString:#"https://graph.facebook.com/me"];
SLRequest *request = [SLRequest requestForServiceType:SLServiceTypeFacebook
requestMethod:SLRequestMethodGET
URL:requestURL
parameters:nil];
request.account = self.facebookAccount;
[request performRequestWithHandler:^(NSData *data,
NSHTTPURLResponse *response,
NSError *error)
{
if(!error)
{
list =[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSLog(#"Dictionary contains: %#", list );
if([list objectForKey:#"error"]!=nil)
{
[self attemptRenewCredentials];
}
dispatch_async(dispatch_get_main_queue(),^{
});
}
else
{
[self performSelectorOnMainThread:#selector(hideLoader) withObject:nil waitUntilDone:YES];
NSLog(#"error from get%#",error);
}
}];
}
-(void)attemptRenewCredentials{
[self.accountStore renewCredentialsForAccount:(ACAccount *)self.facebookAccount completion:^(ACAccountCredentialRenewResult renewResult, NSError *error){
if(!error)
{
switch (renewResult) {
case ACAccountCredentialRenewResultRenewed:
NSLog(#"Good to go");
[self get];
break;
case ACAccountCredentialRenewResultRejected:
{
NSLog(#"User declined permission");
UIAlertView* alt = [[UIAlertView alloc] initWithTitle:#"Access Denied"
message:#"You declined permission" delegate:self cancelButtonTitle:nil otherButtonTitles:#"Ok",nil];
[alt show];
break;
}
case ACAccountCredentialRenewResultFailed:
{
NSLog(#"non-user-initiated cancel, you may attempt to retry");
UIAlertView* alt = [[UIAlertView alloc] initWithTitle:#"Access Denied"
message:#"non-user-initiated cancel, you may attempt to retry" delegate:self cancelButtonTitle:nil otherButtonTitles:#"Ok",nil];
[alt show];
break;
}
default:
break;
}
}
else{
//handle error gracefully
NSLog(#"error from renew credentials%#",error);
}
}];
}
T**o get this code work the bundle Identifier with which you have registered your application with facebook and bundle identifier in application plist file should be same**

How can we post something on facebook in ios 6 like twitter?

I am implementing facebook posting in my app. And add some code to post something on facebook account.
My code is as follows.
- (void)publishStory
{
NSLog(#"publish story called .......");
[FBRequestConnection
startWithGraphPath:#"me/feed"
parameters:self.postParams
HTTPMethod:#"POST"
completionHandler:^(FBRequestConnection *connection,
id result,
NSError *error) {
NSString *alertText;
if (error) {
alertText = [NSString stringWithFormat:
#"error: domain = %#, code = %d",
error.domain, error.code];
} else {
alertText = [NSString stringWithFormat:
#"Posted action, id: %#",
[result objectForKey:#"id"]];
}
// Show the result in an alert
[[[UIAlertView alloc] initWithTitle:#"Result"
message:alertText
delegate:self
cancelButtonTitle:#"OK!"
otherButtonTitles:nil]
show];
}];
}
-(IBAction)cancelButtonAction
{
[[self presentingViewController] dismissViewControllerAnimated:YES completion:nil];
}
-(IBAction)shareButtonAction
{
// Add user message parameter if user filled it in
if (![self.postMessageTextView.text isEqualToString:#""]) {
[self.postParams setObject:self.postMessageTextView.text
forKey:#"message"];
}
// Ask for publish_actions permissions in context
if ([FBSession.activeSession.permissions
indexOfObject:#"publish_actions"] == NSNotFound) {
// No permissions found in session, ask for it
[FBSession.activeSession reauthorizeWithPublishPermissions:
[NSArray arrayWithObjects:#"publish_actions",#"publish_stream", nil]
defaultAudience:FBSessionDefaultAudienceFriends
completionHandler:^(FBSession *session, NSError *error) {
if (!error) {
// If permissions granted, publish the story
NSLog(#"not error");
[self publishStory];
}
}];
} else {
// If permissions present, publish the story
NSLog(#"In else condition");
[self publishStory];
}
}
this is too much code for , "as ios 6 contains integrated facebook in settings."
But I want to post like twitter integration in ios.How can we do that
There are two ways for posting.
1)Post using FBNativeDialog. (inlcude FacebookSDK.framework)
2)Post via SLComposeViewController.
Which one you want to use is up to you.You need to add three frameworks named AdSupport.framework,Accounts.framework and Social.framework.
For using first one you have to include #import "FacebookSDK/FacebookSDK.h" and code for posting is as follows:
UIAlertView *alert=[[UIAlertView alloc] initWithTitle:#"" message:#"" delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil];
BOOL displayedNativeDialog = [FBNativeDialogs presentShareDialogModallyFrom:self initialText:#"" image:[UIImage imageNamed:#"iossdk_logo.png"] url:[NSURL URLWithString:#"https://developers.facebook.com/ios"]
handler:^(FBNativeDialogResult result, NSError *error)
{
if (error) {
alert.message=#"Fail posting due to some error!";
[alert show];
/* handle failure */
} else {
if (result == FBNativeDialogResultSucceeded) {
alert.message=#"Posted Successfully!";
[alert show];
/* handle success */
} else {
/* handle user cancel */
}
}}];
if (!displayedNativeDialog) {
/* handle fallback to native dialog */
}
For second one you need #import "Social/Social.h" and the code is as follows:
SLComposeViewController *fbComposer =
[SLComposeViewController
composeViewControllerForServiceType:SLServiceTypeFacebook];
if([SLComposeViewController isAvailableForServiceType:SLServiceTypeFacebook])
{
SLComposeViewControllerCompletionHandler __block completionHandler=
^(SLComposeViewControllerResult result){
[fbComposer dismissViewControllerAnimated:YES completion:nil];
switch(result){
case SLComposeViewControllerResultCancelled:
default:
{
NSLog(#"Cancelled.....");
}
break;
case SLComposeViewControllerResultDone:
{
NSLog(#"Posted....");
UIAlertView * alert = [[UIAlertView alloc] initWithTitle:#"Sent"
message:nil
delegate:nil
cancelButtonTitle:#"Dismiss"
otherButtonTitles: nil];
[alert show];
}
break;
}};
[fbComposer addImage:[UIImage imageNamed:#"iossdk_logo.png"]];
[fbComposer setInitialText:#"The initial text you want to send"];
[fbComposer addURL:[NSURL URLWithString:#"https://developers.facebook.com/ios"]];
[fbComposer setCompletionHandler:completionHandler];
[self presentViewController:fbComposer animated:YES completion:nil];
}