如果有人通过我的应用登录Facebook,我怎样才能获得用户名?
我正在使用: - FBConnect API。
我的Controller.m文件 -
#import "FacebookPOCViewController.h"
@implementation FacebookPOCViewController
@synthesize session = _session;
@synthesize logoutButton = _logoutButton;
@synthesize loginDialog = _loginDialog;
@synthesize facebookName = _facebookName;
- (void)viewDidLoad {
//PayTai Facebook App
static NSString* kApiKey = @"230600000000";
static NSString* kApiSecret = @"----------------------";
_session = [[FBSession sessionForApplication:kApiKey secret:kApiSecret delegate:self] retain];
// Load a previous session from disk if available. Note this will call session:didLogin if a valid session exists.
[_session resume];
[super viewDidLoad];
}
- (IBAction)loginTapped:(id)sender {
//_posting = YES;
// If we're not logged in, log in first...
if (![_session isConnected]) {
self.loginDialog = nil;
_loginDialog = [[FBLoginDialog alloc] init];
[_loginDialog show];
}
// If we have a session and a name, post to the wall!
else if (_facebookName != nil) {
//[self postToWall];
printf("Session");
}
// Otherwise, we don't have a name yet, just wait for that to come through.
}
- (IBAction)logoutButtonTapped:(id)sender {
[_session logout];
}
#pragma mark FBSessionDelegate methods
- (void)session:(FBSession*)session didLogin:(FBUID)uid {
[self getFacebookName];
}
- (void)session:(FBSession*)session willLogout:(FBUID)uid {
_logoutButton.hidden = YES;
_facebookName = nil;
}
pragma mark Get Facebook Name Helper
- (void)getFacebookName {
NSString* fql = [NSString stringWithFormat:@"select uid,name from user where uid == %lld", _session.uid];
//NSLog(@"%@",_session.uid);
NSDictionary* params = [NSDictionary dictionaryWithObject:fql forKey:@"query"];
[[FBRequest requestWithDelegate:self] call:@"facebook.fql.query" params:params];
}
#pragma mark FBRequestDelegate methods
- (void)request:(FBRequest*)request didLoad:(id)result {
if ([request.method isEqualToString:@"facebook.fql.query"]) {
NSArray* users = result;
NSDictionary* user = [users objectAtIndex:0];
NSString* name = [user objectForKey:@"name"];
self.facebookName = name;
_logoutButton.hidden = NO;
[_logoutButton setTitle:[NSString stringWithFormat:@"Logout as %@", name] forState:UIControlStateNormal];
//if (_posting) {
// [self postToWall];
// _posting = NO;
// }
}
}
答案 0 :(得分:9)
看看这个。您可以使用GRAPH api获取用户的几乎任何信息。
http://developers.facebook.com/docs/reference/api/user/
实施例
/**
* Request the facebook name for the user
* Response will be obtained on delegate
*/
- (void) getFacebookName {
[facebook requestWithGraphPath:@"me?fields=id,name" andDelegate:self];
}
#pragma mark - FBRequestDelegate methods
- (void)request:(FBRequest *)request didLoad:(id)result {
NSLog(@"Result: %@", result);
NSDictionary *userInfo = (NSDictionary *)result;
userName = [userInfo objectForKey:@"name"];
fb_id = [userInfo objectForKey:@"id"];
}