Tweet, without using the tweet sheet - iphone

I'm using below code to share the content (from UITextView, UIImageView) through twitter
-(void)shareViaTweet:(NSString *)shareMessage{
if ([SLComposeViewController isAvailableForServiceType:SLServiceTypeTwitter])
{
SLComposeViewController *tweetSheet = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeTwitter];
[tweetSheet setInitialText:[NSString stringWithFormat:#"%#",shareMessage]];
if (self.imageString)
{
[tweetSheet addImage:[UIImage imageNamed:self.imageString]];
}
if (self.urlString)
{
[tweetSheet addURL:[NSURL URLWithString:self.urlString]];
}
[self presentViewController:tweetSheet animated:YES completion:nil];
}
else
{
UIAlertView *alertView = [[UIAlertView alloc]
initWithTitle:#"Sorry"
message:#"You can't send a tweet right now, make sure your device has an internet connection and you have at least one Twitter account setup"
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];
}
}
But I need share this, without using the pop up view (I think tweet sheet). It's happening because the below code,
[self presentViewController:tweetSheet animated:YES completion:nil];
When I click the button "Share" of my app, I need to post that in twitter.
Edited:
- (IBAction)doneButtonClicked:(id)sender
{
ACAccountStore *account = [[ACAccountStore alloc] init];
ACAccountType *accountType = [account accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];
NSString *message = messageTextView.text;
//hear before posting u can allow user to select the account
NSArray *arrayOfAccons = [account accountsWithAccountType:accountType];
for(ACAccount *acc in arrayOfAccons)
{
NSLog(#"%#",acc.username); //in this u can get all accounts user names provide some UI for user to select,such as UITableview
}
NSURL *url = [NSURL URLWithString:#"https://api.twitter.com"
#"/1.1/statuses/user_timeline.json"];
NSDictionary *params = #{#"screen_name" : message,
#"forKey":#"status",
#"trim_user" : #"1",
#"count" : #"1"};
// Request access from the user to access their Twitter account
[account requestAccessToAccountsWithType:accountType options:nil completion:^(BOOL granted, NSError *error)
{
if (granted == YES)
{
// Populate array with all available Twitter accounts
NSArray *arrayOfAccounts = [account accountsWithAccountType:accountType];
if ([arrayOfAccounts count] > 0)
{
//use the first account available
ACAccount *acct = [arrayOfAccounts objectAtIndex:0]; //hear this line replace with selected account. than post it :)
SLRequest *request =
[SLRequest requestForServiceType:SLServiceTypeTwitter
requestMethod:SLRequestMethodPOST
URL:url
parameters:params];
//Post the request
[request setAccount:acct];
//manage the response
[request performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error)
{
if(error)
{
//if there is an error while posting the tweet
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Twitter" message:#"Error in posting" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
else
{
// on successful posting the tweet
NSLog(#"Twitter response, HTTP response: %i", [urlResponse statusCode]);
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Twitter" message:#"Successfully posted" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
}];
}
else
{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Twitter" message:#"You have no twitter account" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
}
else
{
//suppose user not set any of the accounts
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Twitter" message:#"Permission not granted" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
} ];
//[widgetsHandler closeWidget:nil];
//[self postImage:shareImageView.image withStatus:messageTextView.text];
}
Update: Error

To send images u need do something like this
[account requestAccessToAccountsWithType:accountType withCompletionHandler:^(BOOL granted, NSError *error)
{
if (granted == YES)
{
// Populate array with all available Twitter accounts
NSArray *arrayOfAccounts = [account accountsWithAccountType:accountType];
if ([arrayOfAccounts count] > 0)
{
//use the first account available
ACAccount *acct = [arrayOfAccounts objectAtIndex:0];
//create this request
SLRequest *postRequest = [SLRequest requestForServiceType:SLServiceTypeTwitter requestMethod:SLRequestMethodPOST URL:[NSURL URLWithString:#"https://api.twitter.com"#"/1.1/statuses/update_with_media.json"] parameters: [NSDictionary dictionaryWithObject:message forKey:#"status"]];
UIImage *imageToPost = [UIImage imageNamed:#"image.jpg"];
NSData *imageData = UIImageJPEGRepresentation(imageToPost, 1.0f);//set the compression quality
[postRequest addMultipartData:imageData withName:#"media" type:#"image/jpeg" filename:#"image.jpg"];
//set account and same as above code
....
....

if u wanna share the tweet without using the tweet sheet see my answer it will post on twitter wall without using the tweet sheet see hear and also set the twitter account in the device. hope this helps
unfortunately the class TWRequest is deprecated in iOS 6 but alternatively we can use SLRequest present in the Social framework
the answer for this is similar to the old answer
i commented out something that i dont want but if u want to select which account to use then uncomment the commented code
- (IBAction)doneButtonClicked:(id)sender
{
ACAccountStore *account = [[ACAccountStore alloc] init];
ACAccountType *accountType = [account accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];
NSString *message = _textView.text;
// NSArray *arrayOfAccons = [account accountsWithAccountType:accountType];
// for(ACAccount *acc in arrayOfAccons)
// {
// NSLog(#"%#",acc.username);
// NSDictionary *properties = [acc dictionaryWithValuesForKeys:[NSArray arrayWithObject:#"properties"]];
// NSDictionary *details = [properties objectForKey:#"properties"];
// NSLog(#"user name = %#",[details objectForKey:#"fullName"]);
// NSLog(#"user_id = %#",[details objectForKey:#"user_id"]);
// }
// Request access from the user to access their Twitter account
[account requestAccessToAccountsWithType:accountType withCompletionHandler:^(BOOL granted, NSError *error)
{
if (granted == YES)
{
// Populate array with all available Twitter accounts
NSArray *arrayOfAccounts = [account accountsWithAccountType:accountType];
if ([arrayOfAccounts count] > 0)
{
//use the first account available
ACAccount *acct = [arrayOfAccounts objectAtIndex:0];
// Build a twitter request
// TWRequest *postRequest = [[TWRequest alloc] initWithURL:
// [NSURL URLWithString:#"http://api.twitter.com/1/statuses/update.json"] parameters:[NSDictionary dictionaryWithObject:message forKey:#"status"] requestMethod:TWRequestMethodPOST]; //commented the deprecated method of TWRequest class
SLRequest *postRequest = [SLRequest requestForServiceType:SLServiceTypeTwitter requestMethod:SLRequestMethodPOST URL:[NSURL URLWithString:#"http://api.twitter.com/1/statuses/update.json"] parameters:[NSDictionary dictionaryWithObject:message forKey:#"status"]]; //use this method instead
//Post the request
[postRequest setAccount:acct];//set account
//manage the response
[postRequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error)
{
if(error)
{
//if there is an error while posting the tweet
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Twitter" message:#"Error in posting" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
}
else
{
// on successful posting the tweet
NSLog(#"Twitter response, HTTP response: %i", [urlResponse statusCode]);
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Twitter" message:#"Successfully posted" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
}
}];
}
else
{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Twitter" message:#"You have no twitter account" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
}
}
else
{
//suppose user not set any of the accounts
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Twitter" message:#"You have no twitter account" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
}
} ];
[account release];
}

Related

SWIFT: CDA to iOS 10 Health app

Is there any way to send a xml file (CDA) to health app from another application? Because my application is getting a xml file from a source and I want to send it directly to the new health app (iOS 10).
Create an HKCDADocumentSample and save it with an HKHealthStore.
First, check for authorization
(void) checkForAuthorization {
if ([HKHealthStore isHealthDataAvailable]) {
NSSet *setRead = [NSSet setWithObjects [HKObjectTypedocumentTypeForIdentifier:HKDocumentTypeIdentifierCDA], nil];
NSSet *setWrite = [NSSet setWithObjects:[HKObjectType documentTypeForIdentifier:HKDocumentTypeIdentifierCDA], nil];
[_store requestAuthorizationToShareTypes:setWrite readTypes:nil completion:^(BOOL success, NSError * _Nullable error) {
if (error) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error" message:error.localizedDescription delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[alert show];
} else if (success) {
[self performSelectorOnMainThread:#selector(addDocumentToHealthApp) withObject:nil waitUntilDone:NO];
}
NSLog(#" Success = %#",success? #"YES" : #"NO");
} ];
} else {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error" message:#"Health Kit not supported in device." delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[alert show];
}
}
Second, add Record wmthod this will add a Health record to health app.
(void) addRecordToHealthApp
{
NSURL *cdaPath = [[NSBundle mainBundle] URLForResource:#"sample" withExtension:#"xml"];
NSString*stringPath = [cdaPath absoluteString];
NSData *dataOfCDAFile = [NSData dataWithContentsOfURL:[NSURL URLWithString:stringPath]];
NSDate *now = [NSDate date];
int daysToAdd = 7;
NSDate *newDate1 = [now dateByAddingTimeInterval:60*60*24*daysToAdd];
NSError *err;
HKCDADocumentSample *doc = [HKCDADocumentSample CDADocumentSampleWithData:dataOfCDAFile startDate:[NSDate date] endDate:newDate1 metadata:nil validationError:&err ];
UIAlertView *alert;
if (err) {
alert = [[UIAlertView alloc] initWithTitle:#"Error" message:err.localizedDescription delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[alert show];
}
[_store saveObject:doc withCompletion:^(BOOL success, NSError * _Nullable error) {
NSLog("Stored %#",success?#"YES":#"NO");
}];
}

Facebook return com.facebook.sdk error 5 during Friend Wall Post

In my App I used Facebook sdk 3.1 and using that I try to do wall Post.
Using This Code Snippet I can successfully wall post Image and Message on Friend Wall and on my own wall.I just change me/photos and friendId/photos.
-(IBAction)postPhoto:(id)sender
{
UIImage *image=[UIImage imageNamed:#"baby.jpg"];
NSArray *frndArray=[[NSArray alloc] initWithObjects:#"Friend ID", nil];
[self postImageOnFriendsWall:image FriendsArray:frndArray];
}
-(void)postImageOnFriendsWall:(UIImage*)image FriendsArray:(NSArray*)friends
{
AppDelegate *appDelegate = [[UIApplication sharedApplication]delegate];
// if we don't have permission to announce, let's first address that
if ([appDelegate.session.permissions indexOfObject:#"publish_actions"] == NSNotFound)
{
NSArray *permissions =[NSArray arrayWithObjects:#"publish_actions",#"publish_stream",#"manage_friendlists", nil];
[FBSession setActiveSession:appDelegate.session];
[[FBSession activeSession] reauthorizeWithPublishPermissions:permissions defaultAudience:FBSessionDefaultAudienceFriends completionHandler:^(FBSession *session, NSError *error)
{
if (!error)
{
// have the permission
[self postImageOnFriendsWall:image FriendsArray:friends];
}
else
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error" message:error.localizedDescription delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertView show];
}
}];
}
else
{
//post image
for (id<FBGraphUser> user in friends)
{
NSString* szMessage = #"Check out!";
NSString *userID = user;
NSLog(#"trying to post image of %# wall",userID);
NSMutableDictionary *postVariablesDictionary = [[NSMutableDictionary alloc] init];
[postVariablesDictionary setObject:UIImagePNGRepresentation(image) forKey:#"picture"];
[postVariablesDictionary setObject:szMessage forKey:#"message"];
[FBRequestConnection startWithGraphPath:[NSString stringWithFormat:#"%#/photos",userID] parameters:postVariablesDictionary HTTPMethod:#"POST" completionHandler:^(FBRequestConnection *connection, id result, NSError *error)
{
if (error)
{
//showing an alert for failure
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Facebook"
message:error.localizedDescription delegate:nil cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];
}
else
{
//showing an alert for success
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Facebook"
message:#"Shared the photo successfully" delegate:nil cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];
}
}];
}
}
}
For Message wall post I used me/feed and its work but for Friend friendID/feed will give me Error: HTTP status code: 403 and In alert box i got com.facebook.sdk error 5.
So Please guide me m I doing anything wrong?, or What I have to do for wall post.
Here is solution,
I update my FB SDK 3.1 to 3.2 then import
#import <FacebookSDK/FacebookSDK.h>
then update
[[FBSession activeSession] requestNewPublishPermissions:permissions defaultAudience:FBSessionDefaultAudienceFriends
completionHandler:^(FBSession *session, NSError *error) {}];
in place of
[[FBSession activeSession] reauthorizeWithPublishPermissions:permissions defaultAudience:FBSessionDefaultAudienceFriends completionHandler:^(FBSession *session, NSError *error){}];
and update
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
#"FRIEND ID", #"to",
#"text change", #"caption",
#"this is test message on ur wall", #"description",
#"https://website.com/share", #"link",
#"http://website.com/iossdk_logo.png", #"picture",
nil];
[FBWebDialogs presentFeedDialogModallyWithSession:nil
parameters:params
handler:
^(FBWebDialogResult result, NSURL *resultURL, NSError *error)
{}];
in place of
[FBRequestConnection startWithGraphPath:[NSString stringWithFormat:#"%#/photos",userID] parameters:postVariablesDictionary HTTPMethod:#"POST" completionHandler:^(FBRequestConnection *connection, id result, NSError *error){}];
and i got Dialog box and after click on share Successfully post on FRIEND's Wall.
Hope this snippet help someone else.
I am not sure. Try this one:
me?fields=friends.fields(feed)

Error: HTTP status code: 400 i am getting this while posting data on friend face book wall?

I am selecting the my face book friends in my app i want to post some text data on my friends wall as i pressed the done button when i pressed the done button i am getting this this error.Error: HTTP status code: 400
hehe is my code
- (void)facebookViewControllerDoneWasPressed:(id)sender {
NSMutableString *text = [[NSMutableString alloc] init];
// we pick up the users from the selection, and create a string that we use to update the text view
// at the bottom of the display; note that self.selection is a property inherited from our base class
for (id<FBGraphUser> user in self.friendPickerController.selection) {
NSString *userID = user.id;
NSLog(#"trying to post image of %# wall",userID);
NSMutableDictionary *postVariablesDictionary = [[NSMutableDictionary alloc] init];
//[postVariablesDictionary setObject:UIImagePNGRepresentation(image) forKey:#"picture"];
[postVariablesDictionary setObject:#"my image" forKey:#"message"];
[FBRequestConnection startWithGraphPath:[NSString stringWithFormat:#"%#/photos",userID] parameters:postVariablesDictionary HTTPMethod:#"POST" completionHandler:^(FBRequestConnection *connection, id result, NSError *error)
{
if (error)
{
//showing an alert for failure
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Facebook" message:error.localizedDescription delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertView show];
}
else
{
//showing an alert for success
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Facebook" message:#"Shared the photo successfully" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertView show];
}
}];
}
NSLog(#"%#",text);
[self fillTextBoxAndDismiss];
}

How to post image along with Text using Graph api?

the below code successfuly post my text on facebook wall now i want to post a image along with text using Below code
- (IBAction)callFacebookAPI:(id)sender
{
[self.txtinputfield resignFirstResponder];
if (txtinputfield.text.length !=0)
{
//create the instance of graph api
objFBGraph = [[FbGraph alloc]initWithFbClientID:FbClientID];
//mark some permissions for your access token so that it knows what permissions it has
[objFBGraph authenticateUserWithCallbackObject:self andSelector:#selector(FBGraphResponse) andExtendedPermissions:#"user_photos,user_videos,publish_stream,offline_access,user_checkins,friends_checkins,publish_checkins,email"];
}
else
{
UIAlertView *objAlert = [[UIAlertView alloc]initWithTitle:#"Alert" message:#"Kindly enter data in the text field" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[objAlert show];
}
}
- (void)FBGraphResponse
{
#try
{
if (objFBGraph.accessToken)
{
SBJSON *jsonparser = [[SBJSON alloc]init];
FbGraphResponse *fb_graph_response = [objFBGraph doGraphGet:#"me" withGetVars:nil];
NSString *resultString = [NSString stringWithString:fb_graph_response.htmlResponse];
NSDictionary *dict = [jsonparser objectWithString:resultString];
NSLog(#"Dict = %#",dict);
NSMutableDictionary *variable = [[NSMutableDictionary alloc]initWithCapacity:1];
[variable setObject:txtinputfield.text forKey:#"message"];
[objFBGraph doGraphPost:#"me/feed" withPostVars:variable];
UIAlertView *objAlert = [[UIAlertView alloc]initWithTitle:#"Alert" message:#"String posted on your wall and you may check the console now" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[objAlert show];
}
}
#catch (NSException *exception) {
UIAlertView *objALert = [[UIAlertView alloc]initWithTitle:#"Alert" message:[NSString stringWithFormat:#"Something bad happened due to %#",[exception reason]] delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[objALert show];
}
txtinputfield.text = clearText;
}
I tried some methods but did'nt work for me, i have no experience with Graph Api Any help will be appriated.Thanks
Try like below:
- (IBAction)buttonClicked:(id)sender
{
NSArray* permissions = [[NSArray alloc] initWithObjects:
#"publish_stream", nil];
[facebook authorize:permissions delegate:self];
[permissions release];
}
- (void)fbDidLogin
{
NSString *filePath =pathToImage;
NSData *videoData = [NSData dataWithContentsOfFile:filePath];
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
videoData, pathToImage,
#"picture/jpeg", #"contentType",
#"Video Test Title", #"title",
#"Video Test Description", #"description",
nil];
[facebook requestWithGraphPath:#"me/photos"
andParams:params
andHttpMethod:#"POST"
andDelegate:self];
}
-(void)fbDidNotLogin:(BOOL)cancelled
{
NSLog(#"did not login");
}
- (void)request:(FBRequest *)request didLoad:(id)result
{
if ([result isKindOfClass:[NSArray class]])
{
result = [result objectAtIndex:0];
}
NSLog(#"Result of API call: %#", result);
}
- (void)request:(FBRequest *)request didFailWithError:(NSError *)error
{
NSLog(#"Failed with error: %#", [error localizedDescription]);
}

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**