状況
- Facebook for iOS SDKを使用
-
FBSDKLoginButton
にてログインはできる -
FBSDKLoginButtonDelegate
のloginButton:didCompleteWithResult:error
で値を設定しようと試みる-
FBSDKProfilePictureView
にはプロフィールイメージが表示される - にもかかわらず何故か
FBSDKProfile
がnil
となり名前が取得できない
-
ちなみに最初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: enableUpdatesOnAccessTokenChange
をYES
にしていなかった
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]
を取得することができました。