LoginSignup
1
1

More than 5 years have passed since last update.

Facebook連携でFBSDKProfileがnilになる問題の解決方法

Last updated at Posted at 2015-06-20

状況

  • Facebook for iOS SDKを使用
  • FBSDKLoginButtonにてログインはできる
  • FBSDKLoginButtonDelegateloginButton:didCompleteWithResult:errorで値を設定しようと試みる
    • FBSDKProfilePictureViewにはプロフィールイメージが表示される
    • にもかかわらず何故かFBSDKProfilenilとなり名前が取得できない

ちなみに最初delegateメソッドが呼ばれなくて焦っていたんですがdelegateの登録し忘れるという初歩的なミスをしてました。

原因

Facebook SDK v4.0 for iOS - FBSDKProfile currentProfile not being setが大変参考になりました。

原因その1: 取得のタイミングが悪かった

名前取得を行うタイミングはloginButton:didCompleteWithResult:errorではなく、ObserverのFBSDKProfileDidChangeNotificationでした。

viewDidLoad内
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(observeProfileChange:) name:FBSDKProfileDidChangeNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(observeTokenChange:) name:FBSDKAccessTokenDidChangeNotification object:nil];
呼ばれるメソッド
- (void)observeProfileChange:(NSNotification *)notfication {
    if ([FBSDKProfile currentProfile]) {
        self.nameLabel.text = [FBSDKProfile currentProfile].name;
    }
}

- (void)observeTokenChange:(NSNotification *)notfication {
    if ([FBSDKAccessToken currentAccessToken]) {
       [self observeProfileChange:nil];
    }
}

原因その2: enableUpdatesOnAccessTokenChangeYESにしていなかった

Facebook SDK v4.0 for iOS - FBSDKProfile currentProfile not being setにあるように、AppDelegate.mで設定する必要がありました。

AppDelegate.m
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [FBSDKProfile enableUpdatesOnAccessTokenChange:YES];
    return [[FBSDKApplicationDelegate sharedInstance] application:application didFinishLaunchingWithOptions:launchOptions];
}

以上で無事[FBSDKProfile currentProfile]を取得することができました。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1