首先,您无法检索用户的 Facebook密码。希望原因很明显。
但是,您可以在您使用 ShareKit 将您的应用连接到用户的 Facebook 帐户后检索您的应用获得的访问令牌。
在撰写本文时,我不相信 ShareKit 可以直接访问访问令牌,但有一个简单的方法可以检索它。
第 1 步:确保您的应用有权连接到 Facebook
BOOL isConnected = [SHKFacebook isServiceAuthorized];
如果您在此处收到isConnected == NO,您的 UI 应指示用户需要连接到 Facebook 才能使用您的分享功能。
第 2 步:获取访问令牌以访问用户的 Facebook 数据
假设您在步骤 1 中获得了 isConnected == YES
// Hack into ShareKit's user defaults
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *accessToken = [defaults valueForKey:@"kSHKFacebookAccessToken"];
第 3 步:绕过 ShareKit 并对 Facebook SDK 进行自定义查询
假设你的类中有一个属性,比如这个......
// Change "strong" to "retain" if not using ARC
@property (nonatomic, strong) SHKFacebook *shkFb;
...您可以使用类似这样的方式开始 Facebook 查询...
if ( !fb ) {
// This is how SHKFacebook instantiates a Facebook object. YMMV.
self.fb = [[Facebook alloc] initWithAppId:SHKCONFIG(facebookAppId)];
}
NSMutableDictionary *fbParams = [NSMutableDictionary dictionaryWithObjectsAndKeys:
@"name", @"fields",
accessToken, @"access_token",
nil];
[fb requestWithGraphPath:@"me" andParams:fbParams andDelegate:self];
第 4 步:实现 Facebook 委托方法
Facebook 查询完成后,它会通知您的对象,此时您可以做一些花哨的事情,例如显示用户的姓名,以明确谁的墙会收到从您的应用发送的帖子。
当然,您需要在 .h 中声明 FBRequestDelegate 协议:
#import "Facebook.h"
@interface YourClass : NSObject <FBRequestDelegate>
您需要(最少)实现 FBRequestDelegate 的成功和失败方法:
#pragma mark - FBRequestDelegate
- (void)request:(FBRequest *)request didLoad:(id)result {
// Additional keys available in "result" can be found here:
// https://developers.facebook.com/docs/reference/api/user/
NSString *username = [result objectForKey:@"name"];
// Localize if you're at all interested in the global app market!
NSString *localizedString = NSLocalizedString(@"connected as %@",
@"Connection status label");
// The label will read "connected as <username>"
self.statusLabel.text = [NSString stringWithFormat:localizedString, username];
}
- (void)request:(FBRequest *)request didFailWithError:(NSError *)error {
// Handle failure
// (In our app, we call [SHKFacebook logout]
// and display an error message to the user with
// an option to retry connecting to Facebook.)
}