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.
Related
- (void)viewDidLoad {
[super viewDidLoad];
if (NO == [SLComposeViewController isAvailableForServiceType: SLServiceTypeFacebook]) {
[self showAlert:#"There are no Facebook accounts configured. Please add or create a Facebook account in Settings."];
return;
}
[self getMyDetails];
// Do any additional setup after loading the view from its nib.
}
- (void) getMyDetails {
if (! accountStore) {
accountStore = [[ACAccountStore alloc] init];
}
if (! facebookAccountType) {
facebookAccountType = [accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook];
}
NSDictionary *options = #{ ACFacebookAppIdKey: [NSString stringWithFormat:#"1725978560966525"] };
[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 *responseDictionary = [NSJSONSerialization JSONObjectWithData:responseData
options:NSJSONReadingMutableContainers
error:nil];
NSLog(#"id: %#", responseDictionary[#"id"]);
NSLog(#"first_name: %#", responseDictionary[#"first_name"]);
NSLog(#"last_name: %#", responseDictionary[#"last_name"]);
NSLog(#"gender: %#", responseDictionary[#"gender"]);
NSLog(#"city: %#", responseDictionary[#"location"][#"name"]);
}];
} else {
[self showAlert:#"Facebook access for this app has been denied. Please edit Facebook permissions in Settings."];
}
}];
}
- (void) showAlert:(NSString*) msg {
dispatch_async(dispatch_get_main_queue(), ^(void) {
UIAlertView *alertView = [[UIAlertView alloc]
initWithTitle:#"WARNING"
message:msg
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];
});
}
i tried this for getting personal information of Facebook (Logged-in User), But it require permission, as i don't know where To add permissions, i have checked in setting, tried all thing in Simulator But Still Not getting.
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 want to send the messages and want to post on facebook and twitter in background is there any possible framework is there to do this.Can any one share the idea please.Thanks in advance .
To post on Twitter in background use this library https://github.com/nst/STTwitter
You will need to register your app on Twitter to receive consumer key and consumer secret. After you have it just use the code represented here Accessing Twitter Direct Messages using SLRequest iOS. This code uses system Twitter credentials, user have to set these credentials in iPhone / iPad settings.
Regarding to post on Facebook: I found no wrapper for iOS which can provide possibility to post in background. I use official Facebook iOS SDK is here https://github.com/facebook/facebook-ios-sdk. But post functionality works only with user's participation.
For facebook make sure you have the user permission or sdk setup properly. I would recommend to go through this tutorial for details.
http://m-farhan.com/2014/03/ios-facebook-sdk-tutorial/
- (void)requestPermissionAndPost {
[FBSession.activeSession requestNewPublishPermissions:[NSArray arrayWithObjects:#"publish_actions", #"publish_checkins",nil]
defaultAudience:FBSessionDefaultAudienceEveryone
completionHandler:^(FBSession *session, NSError *error) {
if (!error) {
// Now have the permission
[self postOpenGraphAction];
} else {
// Facebook SDK * error handling *
// if the operation is not user cancelled
if (error.fberrorCategory != FBErrorCategoryUserCancelled) {
[self presentAlertForError:error];
}
}
}];
}
- (void)postOpenGraphAction
{
FBRequestConnection *newConnection = [[FBRequestConnection alloc] init];
FBRequestHandler handler =
^(FBRequestConnection *connection, id result, NSError *error) {
// output the results of the request
[self requestCompleted:connection forFbID:#"me" result:result error:error];
};
UIImage *img = imageView.image;
NSString *message = #"Your Message";
FBRequest *request=[[FBRequest alloc] initWithSession:FBSession.activeSession graphPath:#"me/photos" parameters:[NSDictionary dictionaryWithObjectsAndKeys:UIImageJPEGRepresentation(img, 0.7),#"source",message,#"message",#"{'value':'EVERYONE'}",#"privacy", nil] HTTPMethod:#"POST"];
[newConnection addRequest:request completionHandler:handler];
[self.requestConnection cancel];
self.requestConnection = newConnection;
[newConnection start];
}
// FBSample logic
// Report any results. Invoked once for each request we make.
- (void)requestCompleted:(FBRequestConnection *)connection
forFbID:fbID
result:(id)result
error:(NSError *)error
{
NSLog(#"request completed");
// not the completion we were looking for...
if (self.requestConnection &&
connection != self.requestConnection)
{
NSLog(#" not the completion we are looking for");
return;
}
// clean this up, for posterity
self.requestConnection = nil;
if (error)
{
NSLog(#" error");
UIAlertView *alert=[[UIAlertView alloc] initWithTitle:#"error" message:error.localizedDescription delegate:nil cancelButtonTitle:#"OK" otherButtonTitles: nil];
// error contains details about why the request failed
[alert show];
}
else
{
NSLog(#" ok");
NSLog(#"%#",result);
/*[[[UIAlertView alloc] initWithTitle:#"Result"
message:[NSString stringWithFormat:#"Posted Open Graph action, id: %#",
[result objectForKey:#"id"]]
delegate:nil
cancelButtonTitle:#"Thanks!"
otherButtonTitles:nil]
show];*/
[self doCheckIn];
};
}
fro Twitter its simple and easy
#import <Twitter/Twitter.h>
- (void)TWPostImage:(UIImage *)image withStatus:(NSString *)status
{
ACAccountStore *accountStore = [[ACAccountStore alloc] init];
//ACAccountStore *accountStore = [[ACAccountStore alloc] init];
// Create an account type that ensures Twitter accounts are retrieved.
ACAccountType *accountType = [accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];
[accountStore requestAccessToAccountsWithType:accountType withCompletionHandler:^(BOOL granted, NSError *error) {
ACAccount *ac;
if(granted) {
NSArray *accountsArray = [accountStore accountsWithAccountType:accountType];
int i=0;
for (ACAccount *account in accountsArray ) {
i++;
NSLog(#"Account name: %#", account.username);
ac=account;
}
if (i==0) {
[[[UIAlertView alloc] initWithTitle:#"Wait"
message:#"Please setup Twitter Account Settigns > Twitter > Sign In "
delegate:nil
cancelButtonTitle:#"Thanks!"
otherButtonTitles:nil]
show];
return ;
}
ACAccountType *twitterType = [accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];;
//SLRequestHandler requestHandler;
SLRequestHandler requestHandler =
^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
dispatch_async(dispatch_get_main_queue(), ^{
if (responseData) {
NSInteger statusCode = urlResponse.statusCode;
if (statusCode >= 200 && statusCode < 300) {
NSDictionary *postResponseData =
[NSJSONSerialization JSONObjectWithData:responseData
options:NSJSONReadingMutableContainers
error:NULL];
NSLog(#"[SUCCESS!] Created Tweet with ID: %#", postResponseData[#"id_str"]);
ESAppDelegate* d =[[UIApplication sharedApplication] delegate];
NSString* link = [NSString stringWithFormat:#"Your Message",twitterAccStore,hashtagFromStore];
[d linkSelected:link PointerToSelf:self];
/*[[[UIAlertView alloc] initWithTitle:#"Result"
message:[NSString stringWithFormat:#"[SUCCESS!] Created Tweet with ID: %#", postResponseData[#"id_str"]]
delegate:nil
cancelButtonTitle:#"Thanks!"
otherButtonTitles:nil]
show];*/
}
else {
NSLog(#"[ERROR] Server responded: status code %d %#", statusCode,
[NSHTTPURLResponse localizedStringForStatusCode:statusCode]);
}
}
else {
NSLog(#"[ERROR] An error occurred while posting: %#", [error localizedDescription]);
}
});
};
//});
ACAccountStoreRequestAccessCompletionHandler accountStoreHandler =
^(BOOL granted, NSError *error) {
if (granted) {
NSArray *accounts = [accountStore accountsWithAccountType:twitterType];
NSURL *url = [NSURL URLWithString:#"https://api.twitter.com"
#"/1.1/statuses/update_with_media.json"];
NSDictionary *params = #{#"status" : status};
SLRequest *request = [SLRequest requestForServiceType:SLServiceTypeTwitter
requestMethod:SLRequestMethodPOST
URL:url
parameters:params];
NSData *imageData = UIImageJPEGRepresentation(image, 1.f);
[request addMultipartData:imageData
withName:#"media[]"
type:#"image/jpeg"
filename:#"image.jpg"];
[request setAccount:[accounts lastObject]];
[request performRequestWithHandler:requestHandler];
//});
}
else {
NSLog(#"[ERROR] An error occurred while asking for user authorization: %#",
[error localizedDescription]);
}
};
[accountStore requestAccessToAccountsWithType:twitterType
options:NULL
completion:accountStoreHandler];
}else
{
[[[UIAlertView alloc] initWithTitle:#"Wait"
message:#"Please Settigns > Twitter > In bottom Enable DealsHype to post"
delegate:nil
cancelButtonTitle:#"Thanks!"
otherButtonTitles:nil]
show];
}
}];
}
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"];
}];
}
}
I am trying to implement "Follow Us On Twitter" in my iOS app. Here is my code. But it give error "Could not prepare the URL request". Please help!
ACAccountStore *accountStore = [[ACAccountStore alloc] init];
ACAccountType *accountType = [accountStore
accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];
[accountStore
requestAccessToAccountsWithType:accountType
options:NULL
completion:^(BOOL granted, NSError *error) {
if (granted) {
NSMutableDictionary *tempDict = [[NSMutableDictionary alloc] init];
[tempDict setValue:#"a4arpan" forKey:#"screen_name"];
[tempDict setValue:#"true" forKey:#"follow"];
SLRequest *postRequest = [SLRequest requestForServiceType:SLServiceTypeTwitter
requestMethod:SLRequestMethodPOST
URL:[NSURL URLWithString:#"https://api.twitter.com/1.1/friendships/create.json"]
parameters:tempDict];
ACAccount * twitterAccount = [[ACAccount alloc] initWithAccountType:accountType];
twitterAccount.username = twitterUsername;
[postRequest setAccount:twitterAccount];
[postRequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
if (responseData) {
if (urlResponse.statusCode >= 200 && urlResponse.statusCode < 300) {
NSError *jsonError;
NSDictionary *timelineData =
[NSJSONSerialization
JSONObjectWithData:responseData
options:NSJSONReadingAllowFragments error:&jsonError];
if (timelineData) {
NSLog(#"Timeline Response: %#\n", timelineData);
}
else {
// Our JSON deserialization went awry
NSLog(#"JSON Error: %#", [jsonError localizedDescription]);
}
if ([urlResponse statusCode] == 200) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Follow us successfull" message:nil delegate:nil cancelButtonTitle:#"Thanx" otherButtonTitles:nil, nil];
[alert show];
}
else {
if ([tpAppMode isEqualToString:#"sandbox"])
NSLog(#"%#", [error localizedDescription]);
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Follow us Failed" message:nil delegate:nil cancelButtonTitle:#"Thanx" otherButtonTitles:nil, nil];
[alert show];
}
}
else {
// The server did not respond successfully... were we rate-limited?
NSLog(#"The response status code is %d", urlResponse.statusCode);
}
}
else {
NSString *output = [NSString stringWithFormat:#"HTTP response status: %# %#", [error localizedDescription], [error localizedFailureReason]];
NSLog(#"%#", output);
}
}];
}
else {
if ([tpAppMode isEqualToString:#"sandbox"])
NSLog(#"%#", [error localizedDescription]);
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Follow us Failed" message:nil delegate:nil cancelButtonTitle:#"Thanx" otherButtonTitles:nil, nil];
[alert show];
}
}];
I have followed all the steps mentioned on Twitter Dev
That is how I've done it!
SLRequest *request = [SLRequest requestForServiceType:SLServiceTypeTwitter requestMethod:SLRequestMethodPOST URL:[NSURL URLWithString:#"https://api.twitter.com/1.1/friendships/create.json"] parameters:[NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:#"AnatoliyGatt", #"true", nil] forKeys:[NSArray arrayWithObjects:#"screen_name", #"follow", nil]]];
[request setAccount:[[self twitterAccounts] lastObject]];
[request performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
if(responseData) {
NSDictionary *responseDictionary = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:&error];
if(responseDictionary) {
// Probably everything gone fine
}
} else {
// responseDictionary is nil
}
}];