未安装Facebook应用时首次分享成功后调用sharerDidCancel:的问题
嘿,这个问题我之前做iOS Facebook分享时也碰到过!本质是Facebook SDK 4.x版本在浏览器模式下的一个回调判定bug,咱们一步步来解决它。
问题还原
你用UIButton结合Facebook SDK 4.31.1实现分享功能,当设备没装Facebook App时,首次分享明明成功完成了,结果回调却走到了sharerDidCancel:方法,而非预期的成功回调。你的核心代码大概是这样的(补全了你截断的部分):
- (IBAction)btnSharePressed:(id)sender { [self displayShareDialog]; } - (void)displayShareDialog { FBSDKShareLinkContent *content = [self getShareContent]; if ([FacebookHandler isFacebookAppInstalled]) { [FBSDKShareDialog showFromViewController:self withContent:content delegate:self]; } else { FBSDKShareDialog * shareDialog = [[FBSDKShareDialog alloc] init]; [shareDialog setMode:FBSDKShareDialogModeBrowser]; // 推测你设置的是浏览器模式 shareDialog.viewController = self; shareDialog.shareContent = content; shareDialog.delegate = self; [shareDialog show]; } }
问题原因
这是Facebook SDK 4.31.x版本的已知问题:当首次通过浏览器完成分享后,SDK跳转回App时,状态校验逻辑出现偏差,把成功的分享操作误判成了用户取消操作。
两种解决办法任你选
办法1:改用Web内嵌模式+修正回调判断
把分享模式改成FBSDKShareDialogModeWeb(内嵌Web页,而非外部浏览器),同时在回调里加一层校验,避免误判:
- (void)displayShareDialog { FBSDKShareLinkContent *content = [self getShareContent]; if ([FacebookHandler isFacebookAppInstalled]) { [FBSDKShareDialog showFromViewController:self withContent:content delegate:self]; } else { FBSDKShareDialog *shareDialog = [[FBSDKShareDialog alloc] init]; shareDialog.mode = FBSDKShareDialogModeWeb; // 换用内嵌Web模式 shareDialog.viewController = self; shareDialog.shareContent = content; shareDialog.delegate = self; [shareDialog show]; } } // 重写分享回调 - (void)sharerDidCancel:(id<FBSDKSharing>)sharer { // 针对Web模式,额外检查是否真的取消了 if ([(FBSDKShareDialog *)sharer mode] == FBSDKShareDialogModeWeb) { // 通过检查有效登录令牌,判断是否实际分享成功 if (FBSDKAccessToken.currentAccessToken) { // 这里其实是分享成功,执行你的成功逻辑 [self handleShareSuccess]; return; } } // 真正的取消操作,执行取消逻辑 [self handleShareCancel]; } - (void)sharer:(id<FBSDKSharing>)sharer didCompleteWithResults:(NSDictionary *)results { [self handleShareSuccess]; }
办法2:升级Facebook SDK到新版本
Facebook在4.40.0及以上的版本里修复了这个回调bug,如果你的项目允许升级SDK,直接把版本升到4.40.0+,不用修改现有代码就能正常触发成功回调,这是最省心的办法。
额外提醒
- 确保你的App已经正确配置了Facebook的URL Scheme,不然浏览器跳转回App时无法传递状态,还是会出问题。
- 测试时记得清理App缓存和Facebook的浏览器登录状态,避免旧数据干扰测试结果。
内容的提问来源于stack exchange,提问作者Got99Errors
相关产品推荐
相关产品推荐

