Getting Facebook user info after login in objective c - objective-c

I'm trying to get the user name, email and picture from Facebook after login. Login and permissions works fine.
I tried using:
FBSession
But Im getting "user of undeclared FBSession" as I was trying to implement:
if (FBSession.activeSession.isOpen) {
[[FBRequest requestForMe] startWithCompletionHandler:
^(FBRequestConnection *connection,
NSDictionary<FBGraphUser> *user,
NSError *error) {
if (!error) {
NSString *firstName = user.first_name;
NSString *lastName = user.last_name;
NSString *facebookId = user.id;
NSString *email = [user objectForKey:#"email"];
NSString *imageUrl = [[NSString alloc] initWithFormat: #"http://graph.facebook.com/%#/picture?type=large", facebookId];
}
}];}
Found it here: How to get user info from Facebook SDK in iOS?
Any ideas how can I achive this? Or why am I getting undeclared for Facebook elements?

If you are using the new facebook sdk and new graph api you have to use access tokens
if ([FBSDKAccessToken currentAccessToken]) {
[[[FBSDKGraphRequest alloc] initWithGraphPath:#"me" parameters:#{#"fields": #"picture,email,birthday,gender,name"}] startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id res, NSError *error)
{
if (!error) {
FBID = [res objectForKey:#"id"];
FBDOB = [res objectForKey:#"birthday"];
FBEMAIL = [res objectForKey:#"email"];
FBGENDER = [res objectForKey:#"gender"];
FBUSERNAME = [res objectForKey:#"name"];
}
else
{
NSLog(#"%#", [error localizedDescription]);
}}];
}
check out this link on fetching data from facebook
https://developers.facebook.com/docs/ios/graph

Related

Fetch only MyContacts from gmail account in iOS

I am trying to fetch gmail & yahoo contacts in my iPhone application.
For Gmail I have used GTMOauth2.0. I can see all contacts but when I want only contacts from MyContacts group. I have used following code to get contacts:
-(void)signInToGoogle:(id)sender
{
[self signOutFromGoogle];
NSString *keychainItemName = nil;
NSString *scope = #"https://www.google.com/m8/feeds/contacts/default/full";
NSString *clientID = #"CLIENTID";
NSString *clientSecret = #"CLIENTSECRETID";
SEL finishedSel = #selector(viewController:finishedWithAuth:error:);
GTMOAuth2ViewControllerTouch *viewController;
viewController = [GTMOAuth2ViewControllerTouch controllerWithScope:scope
clientID:clientID
clientSecret:clientSecret
keychainItemName:keychainItemName
delegate:self
finishedSelector:finishedSel];
NSDictionary *params = [NSDictionary dictionaryWithObject:#"en" forKey:#"hl"];
viewController.signIn.additionalAuthorizationParameters = params;
NSString *html = #"<html><body bgcolor=silver><div align=center>Loading sign-in page...</div></body></html>";
viewController.initialHTMLString = html;
[[self navigationController] pushViewController:viewController animated:YES];
}
- (void)viewController:(GTMOAuth2ViewControllerTouch *)viewController
finishedWithAuth:(GTMOAuth2Authentication *)auth
error:(NSError *)error {
[[NSNotificationCenter defaultCenter] removeObserver:self];
if (error != nil) {
[processObj removeFromSuperview];
self.view.userInteractionEnabled = YES;
NSLog(#"Authentication error: %#", error);
NSData *responseData = [[error userInfo] objectForKey:#"data"]; // kGTMHTTPFetcherStatusDataKey
if ([responseData length] > 0) {
// show the body of the server's authentication failure response
NSString *str = [[NSString alloc] initWithData:responseData
encoding:NSUTF8StringEncoding];
NSLog(#"%#", str);
}
self.auth = nil;
} else {
self.auth = auth;
[self doAnAuthenticatedAPIFetch];
}
}
- (void)doAnAuthenticatedAPIFetch {
NSString *urlStr = #"https://www.google.com/m8/feeds/groups/default/full/Contacts";
NSURL *url = [NSURL URLWithString:urlStr];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[self.auth authorizeRequest:request
completionHandler:^(NSError *error) {
NSString *output = nil;
if (error) {
output = [error description];
} else {
NSURLResponse *response = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response
error:&error];
if (data) {
// API fetch succeeded :Here I am getti
output = [[NSString alloc] initWithData:data
encoding:NSUTF8StringEncoding];
} else {
// fetch failed
output = [error description];
}
}
}];
}
In the API I am passing "Contacts" as a group id but it is returning error "Group Id Not Found". I have the google document from
https://developers.google.com/google-apps/contacts/v3/?csw=1
but still can't solve the problem. Help me on these.
You'll need to fetch the groups feed to get the ID for a group. See the groups feed documentation, or try the ContactsSample app provided with the Google Data APIs Objective-C Client Library.

How do I loop through tweets to access geo information and add to an array

How would I loop through the JSON returned by a TWRequest to get the geo information of a tweet? I am using the code below - I have marked up the bit I am unsure about. the text component works fine, I'm just not sure how to create the array of geo data and access this...
- (void)fetchTweets
{
AppDelegate *delegate = (AppDelegate*)[[UIApplication sharedApplication]delegate];
//NSLog(#"phrase carried over is %#", delegate.a);
// Do a simple search, using the Twitter API
TWRequest *request = [[TWRequest alloc] initWithURL:[NSURL URLWithString:
[NSString stringWithFormat:#"http://search.twitter.com/search.json?q=%#", delegate.a]]
parameters:nil requestMethod:TWRequestMethodGET];
// Notice this is a block, it is the handler to process the response
[request performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error)
{
if ([urlResponse statusCode] == 200)
{
// The response from Twitter is in JSON format
// Move the response into a dictionary and print
NSError *error;
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:&error];
//NSLog(#"Twitter response: %#", dict);
NSArray *results = [dict objectForKey:#"results"];
//Loop through the results
for (NSDictionary *tweet in results) {
// Get the tweet
NSString *twittext = [tweet objectForKey:#"text"];
//added this one - need to check id NSString is ok??
NSString *twitlocation = [tweet objectForKey:#"geo"];
// Save the tweet to the twitterText array
[_twitterText addObject:twittext];
//this is the loop for the location
[twitterLocation addObject:twitlocation];
}
dispatch_async(dispatch_get_main_queue(), ^{
[self.tableView reloadData];
});
}
else
NSLog(#"Twitter error, HTTP response: %i", [urlResponse statusCode]);
}];
}
"geo" is deprecated and probably not filled at all. I far as I remember it was deprecated in Twitter API v1.0 too. Try this code:
- (void)fetchTweets
{
AppDelegate *delegate = (AppDelegate*)[[UIApplication sharedApplication]delegate];
//NSLog(#"phrase carried over is %#", delegate.a);
// Do a simple search, using the Twitter API
TWRequest *request = [[TWRequest alloc] initWithURL:[NSURL URLWithString:
[NSString stringWithFormat:#"http://search.twitter.com/search.json?q=%#", delegate.a]]
parameters:nil requestMethod:TWRequestMethodGET];
// Notice this is a block, it is the handler to process the response
[request performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error)
{
if ([urlResponse statusCode] == 200)
{
// The response from Twitter is in JSON format
// Move the response into a dictionary and print
NSError *error;
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:&error];
//NSLog(#"Twitter response: %#", dict);
NSArray *results = [dict objectForKey:#"results"];
//Loop through the results
for (NSDictionary *tweet in results) {
// Get the tweet
NSString *twittext = [tweet objectForKey:#"text"];
//added this one - need to check id NSString is ok??
id jsonResult = [tweet valueForKeyPath:#"coordinates.coordinates"];
if ([NSNull null] != jsonResult) {
if (2 == [jsonResult count]) {
NSDecimalNumber* longitude = [jsonResult objectAtIndex:0];
NSDecimalNumber* latitude = [jsonResult objectAtIndex:1];
if (longitude && latitude) {
// here you have your coordinates do whatever you like
[twitterLocation addObject:[NSString stringWithFormat:#"%#,%#", latitude, longitude]];
}
else {
NSLog(#"Warning: bad coordinates: %#", jsonResult);
}
}
else {
NSLog(#"Warning: bad coordinates: %#", jsonResult);
}
}
// Save the tweet to the twitterText array
[_twitterText addObject:twittext];
}
dispatch_async(dispatch_get_main_queue(), ^{
[self.tableView reloadData];
});
}
else
NSLog(#"Twitter error, HTTP response: %i", [urlResponse statusCode]);
}];
}

Facebook in iOS6.0 use SLRequest to upload a photo failed anyway

Here Comes my Objc code:
ACAccountStore *facebookaccount = [[ACAccountStore alloc] init];
ACAccountType *facebookaccountType = [facebookaccount accountTypeWithAccountTypeIdentifier: ACAccountTypeIdentifierFacebook];
// Specify App ID and permissions
NSDictionary *options = #{ ACFacebookAppIdKey: #"1234567899876543", ACFacebookPermissionsKey: #[#"publish_stream"], ACFacebookAudienceKey: ACFacebookAudienceFriends };
[facebookaccount requestAccessToAccountsWithType:facebookaccountType options:options completion:^(BOOL granted, NSError *error) {
if(granted) {
NSArray *accountsArray = [facebookaccount accountsWithAccountType:facebookaccountType];
if ([accountsArray count] > 0) {
ACAccount *facebookAccount = [accountsArray objectAtIndex:0];
NSString *sendmessage = #"Face";
NSData *myImageData = UIImagePNGRepresentation(imageSource);
SLRequest *facebookRequest = [SLRequest requestForServiceType:SLServiceTypeFacebook requestMethod:SLRequestMethodPOST URL:[NSURL URLWithString:#"https://graph.facebook.com/me/photos"] parameters:nil];
[facebookRequest addMultipartData:myImageData withName:#"source" type:#"multipart/form-data" filename:nil];
[facebookRequest addMultipartData:[sendmessage dataUsingEncoding:NSUTF8StringEncoding] withName:#"message" type:#"multipart/form-data" filename:nil];
[facebookRequest setAccount:facebookAccount];
[facebookRequest performRequestWithHandler:^(NSData* responseData, NSHTTPURLResponse* urlResponse, NSError* error) {
if (error == nil) {
NSLog(#"responedata:%#", [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding]);
}else{
NSLog(#"%#",error.description);
}
}
}
else
{
NSLog(#"error description : %#",[NSString stringWithFormat:#"%#", error.localizedDescription]);
}
}];
Finally I get these respone data:
responedata:{"error":{"message":"(#324) Requires upload file","type":"OAuthException","code":324}}
Help me please!!!
I can successfully upload a photo by including a file name in addMultipartData and by passing the message as part of the SLRequest options.
code:
NSDictionary *parameters = #{#"message": sendmessage};
SLRequest *facebookRequest = [SLRequest requestForServiceType:SLServiceTypeFacebook
requestMethod:SLRequestMethodPOST
URL:[NSURL URLWithString:#"https://graph.facebook.com/me/photos"]
parameters:parameters];
[facebookRequest addMultipartData: myImageData
withName:#"source"
type:#"multipart/form-data"
filename:#"TestImage"];
facebookRequest.account = facebookAccount;
[facebookRequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error)
{
// Log the result
}];

can not get user info after doing authentication,facebookSDK, ios

I am trying to authenticate using facebook account by following
- (IBAction)logInByFaceBook:(id)sender {
NSLog(#"appDelegate.session.isOpen = %#",appDelegate.session.isOpen == 0 ? #"NO" : #"YES");
FBSessionLoginBehavior behavior = FBSessionLoginBehaviorForcingWebView;
appDelegate.session = [[FBSession alloc] init];
[appDelegate.session openWithBehavior:behavior
completionHandler:^(FBSession *session, FBSessionState status, NSError *error) {
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[dict setObject:[NSNumber numberWithBool:YES] forKey:#"didLogIn"];
data = [[SavedData alloc] initLogInInfo:dict];
[data saveLogInInfoToDisk];
if (session.isOpen) {
FBRequest *me = [FBRequest requestForMe];
NSLog(#"me is %#",[me description]);
[me startWithCompletionHandler: ^(FBRequestConnection *connection, NSDictionary<FBGraphUser> *my, NSError *error) {
NSLog(#"my is %#",[my description]);
}
];
}
[self dismissViewControllerAnimated:YES completion:nil];
}
];
}
However, i cant not get my username back and the console is displaying
Error: HTTP status code: 400
my is (null)
By looking up this documentation, 400 means Invalid email address..... and my is null so that I can no extract the username at all.....
I dont know why this happens...I try with the same email address with facebookSDK sample code and it works properly...
Getting lost now....Can somebody point out what I am doing wrong or missing something.

Twitter integration and iOS5: semantic and parsing issues

I was using some of Apple's example code to write the Twitter integration for my app.
However, I get a whopping amount of errors (mostly being Semantic and parse errors).
How can this be solved?
-(IBAction)TWButton:(id)sender {
ACAccountStore *accountstore = [[ACAccountStore alloc] init];
//Make sure to retrive twitter accounts
ACAccountType *accountType = [accountstore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];
[accountstore requestAccessToAccountsWithType:accountType withCompletionHandler:^(BOOL granted, NSError *error) {
if (granted) [{
NSArray *accountsArray = [accountstore accountsWithAccountType:accountType];
if ([accountsArray count] > 0) {
ACAccount *twitterAccount = [accountsArray objectAtIndex:0];
TWRequest *postRequest = [[TWRequest alloc] initWithURL:[NSURL URLWithString:#"http://api.twitter.com/1/statuses/update.json"] parameters:[NSDictionary dictionaryWithObject:[#"Tweeted from iBrowser" forKey:#"status"] requestMethod:TWRequestMethodPOST];
[postRequest setAccount:twitterAccount];
[postRequest preformRequestWithHandeler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
NSString *output = [NSString stringWithFormat:#"HTTP response status: %i", [urlResponse statusCode]];
[self preformSelectorOnMainThread:#selector(displaytext:) withObject:output waitUntilDone:NO];
}];
}
}];
}
//Now lets see if we can actually tweet
-(void)canTweetStatus {
if ([TWTweetComposeViewController canSendTweet]) {
self.TWButton.enabled = YES
self.TWButton.alpha = 1.0f;
}else{
self.TWButton.enabled = NO
self.TWButton.alpha = 0.5f;
}
}
The first error I see is easy to get rid of.
Objective C convention is to make the first letters of each method name lower case.
Use makeKeyAndVisible in your AppDelegate.m
The other errors we'd probably need to see where (in your code) the errors are being thrown, not just what kind of errors.