Extract current facebook username using iOS SDK 4 - ios

I am using Graph API to get facebook user information as follows:
[facebook requestWithGraphPath:#"me" andDelegate:self];
How can I do this? I know that server response is in the form of JSON object but don't know how to parse it.

I don't find the links that helped me to resolve this issue.
This is the code I used (request:didLoad: is a FBRequestDelegate callback):
- (void)request:(FBRequest *)request didLoad:(id)result {
if ([result isKindOfClass:[NSDictionary class]]) {
NSDictionary* hash = result;
NSString *username = (NSString*)[hash valueForKey:#"name"];
[[NSUserDefaults standardUserDefaults] setObject:username forKey:#"Username"];
}
[self publishStream]; // publishStream is a custom methods of mine to create the post to publish
};
I remember that I read the FB ios api code and maybe this and this
I hope this works for you.
Bye,
Fran

I have answered this question here How to retrieve Facebook response using Facebook iOS SDK

Related

iOS google login profileImageURL

- (void)signIn:(GIDSignIn *)signIn didSignInForUser:(GIDGoogleUser *)user
withError:(NSError *)error {
NSString *userId = user.userID;
NSString *idToken = user.authentication.idToken;
NSString *name = user.profile.name;
NSString *email = user.profile.email;
//NSString *Url = user.profile.imageURL;
}
I tried to get google login user details.
How to get profileImageUrl?
any help will be apricated.thanks in advance
Google has defined a method to get Profile image URLs for iOS API. That method is -(NSURL *) imageURLWithDimension:(NSUInteger) dimension. You only need to do the following:
Use this code after signing in:
if(user.profile.hasImage)
{
NSURL *imageURL = [user.profile imageURLWithDimension(50)]; //Give your desired dimenion in parameter.
}
This is defined in Google API documentation.
If you get an unexpected FIFEURL error as some users have in the past, See this already answered question to fix it. But that should not occur again because according to Google:
this is fixed in 2.3.1 that we've just released.
See status on that bug here.
And a suggestion, put your login success code inside a if(!error) clause. Right now you are assuming that a failure in login will never occur. (If you have already done that but didn't show it here then ignore this suggestion).

How to get token info from Sharekit for Twitter

My app displays a short list of tweets based on a given TV hashtag with the additional ability to post a tweet.
But now twitter has gone oauth for all requests, my tweet list doesnt appear as it was using the old search.atom API.
Therefore, how do I access the search api and pass in OAuth credentials using Sharekit so user authenticates just the once for viewing tweets and posting between sessions.
I have tried using SHKRequest, hoping, that as ShareKit has already authorised it will pass this information through; with no joy, is there some other way of doing this or am I just using it badly/wrong.
request = [[[SHKRequest alloc] initWithURL:[NSURL URLWithString:#"https://api.twitter.com/1.1/search/tweets.json?q=twitter&result_type=recent"]
delegate:self
isFinishedSelector:#selector(sendFinishedSearch:)
params:nil
method:#"GET"
autostart:YES] autorelease];
I do need to maintain compatibility with 4.3 API so I cant just use iOS5 Twitter API.
Disclaimer: I am inheriting project from someone so my XCode/ObjC knowledge is being learnt whilst I modify project (I come from C/C++ background), so please ignore my ignorance.
ShareKit contains an SHKTwitter class. It is a subclass of SHKOAuthSharer. As such, you can ask it to perform authorisations / refreshes and get the resulting token.
Create an instance of SHKTwitter and register as it's delegate. Implement the - (void)sharerAuthDidFinish:(SHKSharer *)sharer success:(BOOL)success delegate method. Then call tokenRequest. When the delegate method is called, if success is YES you can get the accessToken.
SHKTwitter *twitter = [[SHKTwitter alloc] init];
twitter.shareDelegate = self;
[twitter tokenRequest];
- (void)sharerAuthDidFinish:(SHKSharer *)sharer success:(BOOL)success
{
SHKTwitter *twitter = (SHKTwitter *)sharer;
if (twitter.accessToken != nil) {
NSLog(#"session: %#, %#", twitterSharer.accessToken.key, twitterSharer.accessToken.secret);
} else {
[twitter tokenAccess];
}
}
IN SHKOAuthSharer.m class You will get access Token in method:
- (void)tokenAccessTicket:(OAServiceTicket *)ticket didFinishWithData:(NSData *)data
{
if (SHKDebugShowLogs) // check so we don't have to alloc the string with the data if we aren't logging
SHKLog(#"tokenAccessTicket Response Body: %#", [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease]);
///[[SHKActivityIndicator currentIndicator] hide];
if (ticket.didSucceed)
{
NSString *responseBody = [[NSString alloc] initWithData:data
encoding:NSUTF8StringEncoding];
//piyush Added
NSArray *strArray = [responseBody componentsSeparatedByString:#"="];
[[NSUserDefaults standardUserDefaults]setObject:[strArray objectAtIndex:([strArray count]-1)] forKey:#"TwitterUsername"];
**self.accessToken** = [[OAToken alloc] initWithHTTPResponseBody:responseBody];
[responseBody release];
[self storeAccessToken];
//[self tryPendingAction];
[[NSNotificationCenter defaultCenter] postNotificationName:#"TwitterDidLogin" object:nil];
}
else
// TODO - better error handling here
[self tokenAccessTicket:ticket didFailWithError:[SHK error:SHKLocalizedString(#"There was a problem requesting access from %#", [self sharerTitle])]];
}

Not receiving response from facebook

I have a problem when I send a post to my wall from my iPhone app.
I have all the delegate methods implemented and the method:
-(void)request:(FBRequest *)request didReceiveResponse:(NSURLResponse *)response {
// Keep this just for testing purposes.
NSLog(#"received response");
}
My app works, the post appears on my wall, but my app doesn't get any response and stucks at my activity indicator. Nothing appears in the console from NSLog.
Does any one know, where's the problem? I'm dying here :-/
EDIT:
- (IBAction)fbButtonPressed:(id)sender {
// Create the parameters dictionary that will keep the data that will be posted.
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
#"330334280387192", #"app_id",
nil];
// Publish.
[self.facebook dialog:#"feed" andParams:params andDelegate:self];
}
I'm using the feed dialog for user input

ios, facebook and getting profile image

I want to get profile image of facebook friends. I know I can do this in code by getting id of user and using this link: userID/picture">http://graph.facebook.com/userID/picture. Is there easier way to get profile image directly from facebook sdk?
The Facebook SDK uses the same user ID and path to its graph. So I think it is not easier. But the same.
what about getting the url of the profile picture? then use something like SDWebImage to display the image and cache it to device. or any open source library that can display and cache image just by passing the url to it?
then, get the userIDs of his friends. save them in NSArray. then create a fql.
-(void)getFriendsInfo:(NSArray*)userIDs
{
//prepare param
NSMutableString *paramStr = [[NSMutableString alloc]init];
for (int i = 0; i<[userIDs count]; i++) {
if ([[userIDs objectAtIndex:i] isKindOfClass:[NSDecimalNumber class]]) {
NSString *tempParam = [NSString stringWithString:[[userIDs objectAtIndex:i]stringValue]];
[paramStr appendFormat:#"'%#',", tempParam];
}
}
[paramStr appendFormat:#"%#",#"'9999999999999'"];
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
[NSString stringWithFormat:#"SELECT uid, name, pic FROM user WHERE uid IN (%#)", tempParam], #"query",
nil];
//in my case, I declared Facebook *facebook; in my app delegate using the latest fb sdk
MyAppDelegate *delegate = (MyAppDelegate *) [[UIApplication sharedApplication] delegate];
[[delegate facebook] requestWithMethodName:#"fql.query"
andParams:params
andHttpMethod:#"POST"
andDelegate:self];
}
handle the data in delegate method
- (void)request:(FBRequest *)request didLoad:(id)result

facebook ios sdk - trouble posting photo using UIImage

I'd be grateful for any suggestions as to how to deal with a problem I'm having posting an image to Facebook.
The following code works just as I would expect:
NSMutableDictionary* params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
#"http://myserver/img.png", #"picture",
#"My Testing", #"name",
#"Enter some text...", #"message",
nil];
[appDelegate.facebook dialog:#"feed" andParams:params andDelegate:self];
However, I really want to use an image that I capture from my camera. I've set up the code to do that earlier in my application and I've put the image on the screen. So, I tried to do this:
CGRect contextRect = CGRectMake(0, 0, 320, 436);
UIGraphicsBeginImageContextWithOptions(contextRect.size, YES, 1);
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
I've tested this code and newImage is a valid UIImage that I can place and manipulate just as I'd expect. However, when I try to integrate it into the Facebook dialog as follows:
NSMutableDictionary* params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
newImage, #"picture",
#"My Testing", #"name",
#"Enter some text...", #"message",
nil];
[appDelegate.facebook dialog:#"feed" andParams:params andDelegate:self];
I get these two ridiculous messages in the console:
-[UIImage length]: unrecognized selector sent to instance 0x1c9420
CoreAnimation: ignoring exception: -[UIImage length]: unrecognized selector sent to instance 0x1c9420
So, as a test, I thought I'd try importing an image into my project and accessing it directly. This is the exact image as I referenced online in the first example, so I know it should work. But even when I try this:
UIImage *newImage = [UIImage imageNamed:#"BaB.png"];
I get the same error messages as above.
I see in the Facebook documentation that the "picture" key is supposed to use the URL to an image. But I've seen some examples online that indicate that folks are using an UIImage instead of just an URL.
Clearly, I'm doing something wrong, but I have no idea what it might be.
I'd be very grateful for any pointers as to how to proceed.
A summarized answer that outlines the process...key point is to include the access_token in the graph calls since the facebook-ios-sdk doesn't do this automatically:
1)Update to the latest facebook-ios-sdk.
2)Instantiate with app id.
self.facebook = [[Facebook alloc] initWithAppId:kApplicationFBID];
3) Authorize the app including publish_stream
NSArray * neededPermissions = [[[NSArray alloc] initWithObjects:#"user_about_me", #"publish_stream", #"user_photos", nil] autorelease];
[facebook authorize:neededPermissions delegate:appDelegate];
4) Ensure app delegate fBDidLogin captures and stores the access token & expiration in user defaults (for later optimization of login process).
-(void)fbDidLogin {
DebugLog(#"New Access Token: %#", [facebook accessToken] );
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:[facebook accessToken] forKey:#"FBAccessTokenKey"];
[defaults setObject:[facebook expirationDate] forKey:#"FBExpirationDateKey"];
[defaults synchronize];
}
5) Confirm valid access token (non nil and not expired)...otherwise re authorize app per above.
6) Capture image to UIImage & call this noting the critical addition of the access_token. This will auto create an album for your app and put the image there and post it on the wall per my testing.
-(void)postImageToAlbum:(UIImage *)image {
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
image, #"source",
#"caption desc", #"message",
nil];
[facebook requestWithGraphPath:[NSString stringWithFormat:#"/me/photos?access_token=%#", self.facebook.accessToken]
andParams:params andHttpMethod:#"POST" andDelegate:self];
}
7) Check for id result in FBRequestDelegate method
-(void)request:(FBRequest *)request didLoad:(id)result {
NSLog(#"Request didLoad: %# ", [request url ]);
if ([result isKindOfClass:[NSArray class]]) {
result = [result objectAtIndex:0];
}
if ([result isKindOfClass:[NSDictionary class]]){
}
if ([result isKindOfClass:[NSData class]]) {
}
NSLog(#"request returns %#",result);
}
8) DO NOT USE a test user account for testing...currently it will auth the test account and provide an access token but when you try to use graph api it will return unexpected errors. You may be alright if you are using web version vs native app setting in dev.facebook.com since supposedly you can create test users and associate them with the app but I haven't tried that.
Good Luck!

Resources