I am new to iOS
I just want to get info such as gender, city, e-mail, and date of birth
but from code which I posted below ,I just got an idea like how to post data on Facebook,
now I want to fetch user details form Facebook
.h
#import <UIKit/UIKit.h>
#import <Social/Social.h>
#interface ViewController : UIViewController
- (IBAction)PostFB:(id)sender;
- (IBAction)PostTW:(id)sender;
#end
.m
//
// ViewController.m
// FaceBookFirstApp3
//
// Created by hits1 on 27/01/14.
// Copyright (c) 2014 hits1. All rights reserved.
//
#import "ViewController.h"
#import <Social/Social.h>
#interface ViewController ()
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)PostFB:(id)sender {
if([SLComposeViewController isAvailableForServiceType:SLServiceTypeFacebook])
{
SLComposeViewController *controller = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeFacebook];
[controller setInitialText:#"First post from my iPhone app"];
[self presentViewController:controller animated:YES completion:Nil];
}
}
- (IBAction)PostTW:(id)sender {
if ([SLComposeViewController isAvailableForServiceType:SLServiceTypeTwitter])
{
SLComposeViewController *tweetSheet = [SLComposeViewController
composeViewControllerForServiceType:SLServiceTypeTwitter];
[tweetSheet setInitialText:#"Great fun to learn iOS programming at appcoda.com!"];
[tweetSheet addURL:[NSURL URLWithString:#"http://www.appcoda.com"]];
[tweetSheet addImage:[UIImage imageNamed:#"socialsharing-facebook-image.jpg"]];
[self presentViewController:tweetSheet animated:YES completion:nil];
}
}
#end
please, help me Out to Fetch at least one field(city (or) gender (or) phone-number) form Gmail or Facebook
You can use the below code to get user's gender, city, e-mail, and date of birth
In .h file add,
#import <Accounts/Accounts.h>
#property (nonatomic, retain) ACAccountStore *accountStore;
#property (nonatomic, retain) ACAccount *facebookAccount;
-(void)get;
-(void)attemptRenewCredentials;
- (void) getuserdetails;
in .m file
- (void) getuserdetails
{
self.accountStore = [[ACAccountStore alloc]init];
ACAccountType *FBaccountType= [self.accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook];
NSString *key = #"your app id";
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 {
dispatch_async(dispatch_get_main_queue(), ^{
// NSLog(#"%#",e.description);
if([e code]== ACErrorAccountNotFound)
{
UIAlertView* alt = [[UIAlertView alloc] initWithTitle:#"Account not found"
message:#"Please setup your Facebook account in Settings App" delegate:self cancelButtonTitle:nil otherButtonTitles:#"Ok",nil];
[alt show];
}
else
{
UIAlertView* alt = [[UIAlertView alloc] initWithTitle:#"Access Denied"
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 );
NSLog(#"EmailID %#",[list objectForKey:#"email"]);
NSLog(#"Birthday %#",[list objectForKey:#"birthday"]);
NSLog(#"Gender %#",[list objectForKey:#"gender"]);
NSLog(#"City %#",[[list objectForKey:#"location"] objectForKey:#"name"]);
if([list objectForKey:#"error"]!=nil)
{
[self attemptRenewCredentials];
}
dispatch_async(dispatch_get_main_queue(),^{
});
}
else{
//handle error gracefully
NSLog(#"error from get%#",error);
//attempt to revalidate credentials
}
}];
}
-(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);
}
}];
}
-(void)accountChanged:(NSNotification *)notif//no user info associated with this notif
{
[self attemptRenewCredentials];
}
- (void)sessionStateChanged:(NSNotification*)notification
{
if (FBSession.activeSession.isOpen)
{
[[FBRequest requestForMe] startWithCompletionHandler:
^(FBRequestConnection *connection, NSDictionary<FBGraphUser> *user, NSError *error)
{
if (!error)
{
//for geting the user detail.
NSString *fbSelectDetails = [#"" stringByAppendingFormat:#"https://graph.facebook.com/me? fields=id,name,email,first_name,last_name,gender,picture,link,birthday,quotes,education&access_token=%#",FBSession.activeSession.accessToken];
NSMutableDictionary *userDetails = [NSMutableDictionary dictionaryWithDictionary:[DataLayer getJSONContentFromURL:fbSelectDetails]];
NSString *uid = [userDetails valueForKey:#"id"];
NSString *userName= user.name;
NSString *userEmail= [userDetails valueForKey:#"email"];
NSString *userFirstName= [userDetails valueForKey:#"first_name"];
NSString *userLastName= [userDetails valueForKey:#"last_name"];
NSString *userGender= [userDetails valueForKey:#"gender"];
NSString *userLink= [userDetails valueForKey:#"link"];
NSString *userDob= [userDetails valueForKey:#"birthday"];
NSMutableDictionary *imgUrl = [NSMutableDictionary dictionaryWithDictionary:[userDetails valueForKey:#"picture"]];
NSString *userImgUrl= [[imgUrl valueForKey:#"data"] valueForKey:#"url"];
}];
}
}
Related
I created a Facebook account, set up Parse.com app and developed iOS application as suggested by Parse.com website. I followed all the steps to make changes in info.plist file and in app delegate class.
Below is my code and I tried to debug it line by line. I noticed that FB asks for user permission and even after accepting it, no further action takes place.
- (IBAction)fblogin:(FBSDKLoginButton *)sender {
NSArray *permissions = #[#"public_profile", #"email"];
[PFFacebookUtils logInInBackgroundWithReadPermissions:permissions block:^(PFUser *user, NSError *error) {
if (error) {
UIAlertView *alertVeiw = [[UIAlertView alloc] initWithTitle:#"Sorry" message:[error.userInfo objectForKey:#"error"] delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alertVeiw show];
} else {
[self loadData];
[self.navigationController popToRootViewControllerAnimated:NO];
}
}];
}
-(void)loadData{
FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc] initWithGraphPath:#"me" parameters:#{#"fields": #"email, public_profile"}];
[request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error)
{
if (!error)
{
// NSDictionary *userData = (NSDictionary *)result;
// NSString *first = [result objectForKey:#"first_name"];
// NSString *last = [result objectForKey:#"last_name"];
// NSString *username = [NSString stringWithFormat:#"%#.%#", first, last];
NSString *name = [result objectForKey:#"name"];
NSString *email = [result objectForKey:#"email"];
PFUser *userFb = [PFUser currentUser];
[userFb setObject:name forKey:#"username"];
[userFb setObject:email forKey:#"email"];
[userFb saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
if (error)
{
UIAlertView *alertVeiw = [[UIAlertView alloc] initWithTitle:#"Sorry" message:[error.userInfo objectForKey:#"error"] delegate:nil cancelButtonTitle:nil otherButtonTitles:nil];
[alertVeiw show];
} else {
[[PFInstallation currentInstallation] setObject:[PFUser currentUser].objectId forKey:#"userId"];
[[PFInstallation currentInstallation] saveInBackground];
// [self.navigationController popToRootViewControllerAnimated:NO];
}
}];
}
}];
}
I couldn't understand why is it not working.
Imported frameworks into .m
#import "LoginViewController.h"
#import <Parse/Parse.h>
#import <FBSDKCoreKit/FBSDKCoreKit.h>
#import <FBSDKLoginKit/FBSDKLoginKit.h>
#import <TwitterKit/TwitterKit.h>
#import <ParseFacebookUtilsV4/PFFacebookUtils.h>
#import "InboxViewController.h"
#import "MBProgressHUD.h"
above is the only login code i have and im not sure why its not working. When i first added and changed the code it would log in and provide a random username. Then when i kept trying different methods and finally ended up with method above it stopped logging in
I am using Login with facebook functionality and get Email Address from facebook. Here is my code.
if (! _accountStore) {
_accountStore = [[ACAccountStore alloc] init];
}
if (! _facebookAccountType) {
_facebookAccountType = [_accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook];
}
NSDictionary *options = #{ ACFacebookAppIdKey:#"1501842240102594" };
[_accountStore requestAccessToAccountsWithType: _facebookAccountType
options: options
completion: ^(BOOL granted, NSError *error) {
if (granted) {
NSArray *accounts = [_accountStore accountsWithAccountType:_facebookAccountType];
_facebookAccount = [accounts lastObject];
NSURL *url = [NSURL URLWithString:#"https://graph.facebook.com/me"];
SLRequest *request = [SLRequest requestForServiceType:SLServiceTypeFacebook
requestMethod:SLRequestMethodGET
URL:url parameters:nil];
request.account = _facebookAccount;
[request performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
NSDictionary *dictionaryForFacebookData = [NSJSONSerialization JSONObjectWithData:responseData
options:NSJSONReadingMutableContainers
error:nil];
//Here dictionaryForFacebookData is dictionary of facebook data.
}
else
{
SLComposeViewController *tweetSheet = [SLComposeViewController
composeViewControllerForServiceType:SLServiceTypeFacebook];
[tweetSheet setInitialText:#"Great fun to learn iOS programming at appcoda.com!"];
[self presentViewController:tweetSheet animated:YES completion:nil];
if ([tweetSheet respondsToSelector:#selector(popoverPresentationController)])
{
// iOS 8+
UIPopoverPresentationController *presentationController = [tweetSheet popoverPresentationController];
presentationController.sourceView = sender; // if button or change to self.view.
}
}
}];
}
Here in SLComposeViewController(else part), it shows some error that is "LaunchServices: invalidationHandler called". Before iOS 8 it present SLComposeViewController to shows user to Login Facebook in setting part.
Please help for this.
With this you can get user details from facebook
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);
}
}];
}
I am new in iOS Development, I am trying to do get Details of User from Facebook. Here is my code which i am used but when it called my app is hang. In below code it can not worked when i can not Login with device in Facebook in Setting>Facebook. Please help me for this.
-(Void)LoginWithFB {
ACAccountStore *accountStore = [[ACAccountStore alloc] init];
ACAccountType *facebookAccountType = [accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook];
SLComposeViewController *vc = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeFacebook];
id options = #{
ACFacebookAppIdKey: #"1501842240102594",
ACFacebookPermissionsKey: #[ #"email"],
};
[accountStore requestAccessToAccountsWithType:facebookAccountType
options:options
completion:^(BOOL granted, NSError *error) {
if (granted)
{
// Return back logined facebook Account
ACAccount *fbAccount = [[accountStore accountsWithAccountType:facebookAccountType] lastObject];
// Do What you want...
// Request friend list
//http://graph.facebook.com/000000000/picture
SLRequest *friendsListRequest = [SLRequest requestForServiceType:SLServiceTypeFacebook
requestMethod:SLRequestMethodGET
URL: [[NSURL alloc] initWithString:#"https://graph.facebook.com/me"]parameters:nil];
friendsListRequest.account = fbAccount;
[friendsListRequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
// Parse response JSON
NSError *jsonError = nil;
NSDictionary *dictionaryForFacebookData = [NSJSONSerialization JSONObjectWithData:responseData
options:NSJSONReadingAllowFragments
error:&jsonError];
// NSString *proficePicture = [NSString stringWithFormat:#"http://graph.facebook.com/415790901901979/picture"];
NSMutableDictionary *dictionaryParameter = [[NSMutableDictionary alloc]init];
[dictionaryParameter setObject:#"facebook" forKey:#"registrationsource"];
[dictionaryParameter setObject:[dictionaryForFacebookData objectForKey:#"first_name"] forKey:#"firstname"];
[dictionaryParameter setObject:[dictionaryForFacebookData objectForKey:#"last_name"] forKey:#"lastname"];
[dictionaryParameter setObject:[dictionaryForFacebookData objectForKey:#"email"] forKey:#"email"];
[dictionaryParameter setObject:#"yes" forKey:#"status"];
WebServiceClass *objectToCallApi = [[WebServiceClass alloc]init];
NSDictionary *dictionaryReturnValue = [objectToCallApi callAPIWebservice:dictionaryParameter stringURL:[[Singelton sharedInstance] passMethodName:#"login"]];
if (![[dictionaryReturnValue objectForKey:#"success"] isEqualToString:#"1"])
{
[UIAlertView showWithTitle:ALERT_TITLE message:[dictionaryReturnValue objectForKey:#"message"] handler:^(UIAlertView *alertview, NSInteger buttonindex){
}];
}
if ([[dictionaryReturnValue objectForKey:#"success"] isEqualToString:#"1"])
{
APP_DELEGATE.intTabbarNumber = 0;
NSMutableDictionary *data =[[NSMutableDictionary alloc]init];
[data setObject:[NSString stringWithFormat:#"%# %#",[dictionaryReturnValue objectForKey:#"firstname"], [dictionaryReturnValue objectForKey:#"lastname"]] forKey:#"fullname"];
[data setObject:dictionaryReturnValue[#"username"] forKey:#"username"];
[data setObject:dictionaryReturnValue[#"email"] forKey:#"email"];
[data setObject:dictionaryReturnValue[#"userid"] forKey:#"userid"];
NSMutableArray *arrayOfExistingUser;
if([[NSUserDefaults standardUserDefaults] valueForKey:#"Users"] != nil)
{
arrayOfExistingUser = [[[NSUserDefaults standardUserDefaults] valueForKey:#"Users"] mutableCopy];
for (int i=0; i<arrayOfExistingUser.count; i++)
{
if ([[[arrayOfExistingUser objectAtIndex:i]objectForKey:#"userid"] isEqualToString:[data objectForKey:#"userid"]])
{
[arrayOfExistingUser removeObjectAtIndex:i];
}
}
}
else
{
arrayOfExistingUser = [[NSMutableArray alloc]init];
}
[arrayOfExistingUser addObject:data];
[[NSUserDefaults standardUserDefaults] setObject:arrayOfExistingUser forKey:#"Users"];
[[NSUserDefaults standardUserDefaults] synchronize];
[[NSUserDefaults standardUserDefaults]setObject:dictionaryReturnValue forKey:#"dictionaryForLoginData"];
if ([[dictionaryReturnValue objectForKey:#"role"] isEqualToString:#"teacher"])
{
[APP_DELEGATE createTabbarInstanceForTeacher];
}
else if ([[dictionaryReturnValue objectForKey:#"role"] isEqualToString:#"student"])
{
[APP_DELEGATE createTabbarInstanceForstudent];
}
else if ([[dictionaryReturnValue objectForKey:#"role"] isEqualToString:#"parent"])
{
[APP_DELEGATE createTabbarInstanceForParent];
}
}
}];
}
else
{
SLComposeViewController *controller = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeFacebook];
[controller.view resignFirstResponder];
controller.view.hidden = YES;
[self presentViewController:controller animated:NO completion:nil];
}
}];
}
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);
}
}];
}
In your method signature - (Void)LoginWithFB; Void is not a type but void is. So that might be the problem.
Hi I am using facebook SDK 3.8 in my project. and using HelloFaceBookSample Code in my app but in my app i have no login button of facebook. I have implemented login flow of facebook and after login i have post on facebook. Now Post Status working fine but when i post image on facebook it give me error of
an attempt was made reauthorize permissions on an unopened session in ios
Code :
-(void) clickButtonFacebookUsingSDK
{
if (!appdelegate.session.isOpen)
{
appdelegate.session = [[FBSession alloc] init];
[appdelegate.session openWithCompletionHandler:^(FBSession *session,
FBSessionState status,
NSError *error) {
if(appdelegate.session.isOpen)
{
NSLog(#"calling postdata when session is not open******");
[self postData];
}
}];
}
else
{
NSLog(#"calling postdata when session is open******");
[self postData];
}
}
-(void) postData
{
[self showingActivityIndicator];
UIImage *img = [UIImage imageNamed:#"abc.jpg"];
[self performPublishAction:^{
FBRequestConnection *connection = [[FBRequestConnection alloc] init];
connection.errorBehavior = FBRequestConnectionErrorBehaviorReconnectSession
| FBRequestConnectionErrorBehaviorAlertUser
| FBRequestConnectionErrorBehaviorRetry;
FBRequest *req = [FBRequest requestForUploadPhoto:img];
[req.parameters addEntriesFromDictionary:[NSMutableDictionary dictionaryWithObjectsAndKeys:message3, #"message", nil]];
[connection addRequest:req
completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
// [self showAlert:#"Photo Post" result:result error:error];
[self showAlert:#"Photo Post" result:result resulterror:error];
if (FBSession.activeSession.isOpen) {
}
}];
[connection start];
}];
}
- (void) performPublishAction:(void (^)(void)) action {
// we defer request for permission to post to the moment of post, then we check for the permission
if ([FBSession.activeSession.permissions indexOfObject:#"publish_actions"] == NSNotFound)
{
// if we don't already have the permission, then we request it now
[FBSession.activeSession requestNewPublishPermissions:#[#"publish_actions"]
defaultAudience:FBSessionDefaultAudienceFriends
completionHandler:^(FBSession *session, NSError *error)
{
if (!error) {
action();
} else if (error.fberrorCategory != FBErrorCategoryUserCancelled){
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Permission denied"
message:#"Unable to get permission to post"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];
}
}];
} else {
action();
}
}
// UIAlertView helper for post buttons
- (void)showAlert:(NSString *)message result:(id)result resulterror:(NSError *)error
{
NSString *alertMsg;
NSString *alertTitle;
if (error)
{
alertTitle = #"Error";
// Since we use FBRequestConnectionErrorBehaviorAlertUser,
// we do not need to surface our own alert view if there is an
// an fberrorUserMessage unless the session is closed.
if (FBSession.activeSession.isOpen) {
alertTitle = #"Error";
} else {
// Otherwise, use a general "connection problem" message.
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";
}
if (alertTitle) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:alertTitle
message:alertMsg
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];
[self dismissActivityIndicator];
}
}
it gives me error in performPublishAction method.
can anyone tell me what is the problem . i have a lot of search and also found many solution but no one work. Please help. Thanks in advance.
I think that you have to set to FBSession what is its active session :
FBSession *session = [[FBSession alloc] init];
[FBSession setActiveSession:session];
It's a sample Twitter application that I made folllowing the tutorial in Apple's developer site. But I don't know what I did wrong for this to happen.
Interface:
#interface TWTViewController : UIViewController {
NSString* output;
}
#property (nonatomic, copy) NSString* output;
- (IBAction)doTweet:(id)sender;
- (IBAction)getTimeline:(id)sender;
#property (weak, nonatomic) IBOutlet UILabel *outputLabel;
#property (weak, nonatomic) IBOutlet UIButton *tweetButton;
#end
Implementation:
#implementation TWTViewController
#synthesize output = _output;
#synthesize outputLabel;
#synthesize tweetButton;
...
- (IBAction)doTweet:(id)sender {
TWTweetComposeViewController *twitter = [[TWTweetComposeViewController alloc] init];
[twitter setInitialText:#"It's really that simple!"];
[twitter addImage:[UIImage imageNamed:#"twitter.png"]];
[self presentViewController:twitter animated:YES completion:nil];
twitter.completionHandler = ^(TWTweetComposeViewControllerResult res) {
if(res == TWTweetComposeViewControllerResultDone) {
UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:#"Success!" message:#"Your Tweet was posted succesfully." delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertView show];
}
else if(res == TWTweetComposeViewControllerResultCancelled) {
UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:#"Error" message:#"Your Tweet was not posted." delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertView show];
}
[self dismissModalViewControllerAnimated:YES];
};
}
- (IBAction)getTimeline:(id)sender {
ACAccountStore* store = [[ACAccountStore alloc] init];
ACAccountType* twitterAccountType = [store accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];
[store requestAccessToAccountsWithType:twitterAccountType withCompletionHandler:^(BOOL granted, NSError *error) {
if(granted) {
NSArray* twitterAccounts = [store accountsWithAccountType:twitterAccountType];
if([twitterAccounts count] > 0) {
ACAccount* account = [twitterAccounts objectAtIndex:0];
NSMutableDictionary* params = [[NSMutableDictionary alloc] init];
[params setObject:#"1" forKey:#"include_entities"];
NSURL* url = [NSURL URLWithString:#"http://api.twitter.com/1/statuses/home_timeline.json"];
TWRequest* request = [[TWRequest alloc] initWithURL:url parameters:params requestMethod:TWRequestMethodGET];
[request setAccount:account];
[request performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
if(error != nil) {
self.output = [error localizedDescription];
self.outputLabel.text = self.output;
}
else {
NSError* jsonError;
NSArray* timeline = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableLeaves error:&jsonError];
if(jsonError == nil) {
self.output = [timeline componentsJoinedByString:#"|"];
self.outputLabel.text = self.output;
}
else {
self.output = [jsonError localizedDescription];
self.outputLabel.text = self.output;
}
}
}];
}
}
}];
}
#end
Here's the ZIP file containing the whole project: http://www.mediafire.com/?yi4x3d6qn1x4p4r
Any help would be greatly appreciated.
Check ALL of your connections in IB. I know it sounds stupid but it gets me all the time...
The "Get Timeline" button is currently set to fire both doTweet: and getTimeline:. Right-click the Get Timeline button in IB and you'll see both listed under Sent Events->Touch Up Inside. Click the little X next to doTweet:, and you should be all good.
#Szwedo's advice is good; always check your connections and actions in IB.