IOS Facebook 3+ 登录 与分享接入

本文详细介绍了如何在iOS应用中集成Facebook SDK,包括初始化过程、登录验证、错误处理及分享功能实现等内容。通过示例代码展示了如何处理登录状态变化、获取用户信息、执行分享操作等关键步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在AppDelegate.m中引入

#import <FacebookSDK/FacebookSDK.h>

首先初始化:

- (BOOL)application:(UIApplication*)application openURL:(NSURL*)url sourceApplication:(NSString*)sourceApplication annotation:(id)annotation
{
// Call FBAppCall's handleOpenURL:sourceApplication to handle Facebook app responses
    BOOL wasHandled = [FBAppCall handleOpenURL:url sourceApplication:sourceApplication];
    
    // You can add your app-specific url handling code here if needed
    
    return wasHandled;
}
- (void)applicationDidBecomeActive:(UIApplication*)application
{
    [FBAppEvents activateApp];
}

配置*.plist

112027_qbCF_699236.png

登录验证接入   接口引入FBLoginViewDelegate

- (void)loginView:(FBLoginView *)loginView handleError:(NSError *)error
{
    NSString *alertMessage, *alertTitle;
    
    // If the user should perform an action outside of you app to recover,
    // the SDK will provide a message for the user, you just need to surface it.
    // This conveniently handles cases like Facebook password change or unverified Facebook accounts.
    if ([FBErrorUtility shouldNotifyUserForError:error]) {
        alertTitle = @"Facebook error";
        alertMessage = [FBErrorUtility userMessageForError:error];
        
        // This code will handle session closures that happen outside of the app
        // You can take a look at our error handling guide to know more about it
        // https://developers.facebook.com/docs/ios/errors
    } else if ([FBErrorUtility errorCategoryForError:error] == FBErrorCategoryAuthenticationReopenSession) {
        alertTitle = @"Session Error";
        alertMessage = @"Your current session is no longer valid. Please log in again.";
        
        // If the user has cancelled a login, we will do nothing.
        // You can also choose to show the user a message if cancelling login will result in
        // the user not being able to complete a task they had initiated in your app
        // (like accessing FB-stored information or posting to Facebook)
    } else if ([FBErrorUtility errorCategoryForError:error] == FBErrorCategoryUserCancelled) {
        NSLog(@"user cancelled login");
        
        // For simplicity, this sample handles other errors with a generic message
        // You can checkout our error handling guide for more detailed information
        // https://developers.facebook.com/docs/ios/errors
    } else {
        alertTitle  = @"Something went wrong";
        alertMessage = @"Please try again later.";
        NSLog(@"Unexpected error:%@", error);
    }
    
    if (alertMessage) {
        [[[UIAlertView alloc] initWithTitle:alertTitle
                                    message:alertMessage
                                   delegate:nil
                          cancelButtonTitle:@"OK"
                          otherButtonTitles:nil] show];
    }
}

- (void)loginViewFetchedUserInfo:(FBLoginView *)loginView
                            user:(id<FBGraphUser>)user
{
    NSLog(@"loginViewFetchedUserInfo");
    FBAccessTokenData *accessTokenData = [[FBSession activeSession] accessTokenData];
    [[NtModule shared] onLoginSuccess:user.id withToken:[accessTokenData accessToken]];
}

// Logged-in user experience
- (void)loginViewShowingLoggedInUser:(FBLoginView *)loginView
{
    NSLog(@"loginViewShowingLoggedInUser");
}

// Logged-out user experience
- (void)loginViewShowingLoggedOutUser:(FBLoginView *)loginView
{
    NSLog(@"loginViewShowingLoggedOutUser");
    [[NtModule shared] onLogout];
}

- (void)onLogout
{
//   sdk登出后处理内容
}

- (NSString *)md5:(NSString *)str
{
    const char *cStr = [str UTF8String];
    unsigned char result[16];
    CC_MD5( cStr, (CC_LONG)strlen(cStr), result );
    
    return [NSString stringWithFormat:
            @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
            result[0], result[1], result[2], result[3],
            result[4], result[5], result[6], result[7],
            result[8], result[9], result[10], result[11],
            result[12], result[13], result[14], result[15]
            ];
}

- (void)onLoginSuccess:(NSString*)userID withToken:(NSString*)token
{
    NSLog(@"onLoginSuccess");
    NSLog(@"%@",userID);
    NSLog(@"%@",token);
    NSLog(@"%@",self.mLoginCallback);
    self.mUserID = userID;
    self.mToken = token;
    
    NSString *tmpString = [self md5:[NSString stringWithFormat:@"%@%@", userID, [NSString stringWithUTF8String:Key]]];
    
    NSMutableDictionary *data = [[NSMutableDictionary alloc] init];
    [data setObject:userID forKey:@"Username"];
    [data setObject:token forKey:@"Password"];
    [data setObject:@"" forKey:@"Error"];
    [data setObject:[NSString stringWithFormat:@"%@:%@", userID, tmpString] forKey:@"SessionID"];
    self.mLoginView.hidden = YES;
    UnitySendMessage("NtModule",
                     [self.mLoginCallback UTF8String],
                     [[NtModule JSONRepresentation:data] UTF8String]);
}

分享接入:

- (void)fbInvite:(NSString*)title withCallback:(NSString*)text withCallback:(NSString*)data withCallback:(NSString *)link withCallback:(NSString *)picUrl
{
    NSLog(@"fbInvite");
    NSLog(@"title:%@", title);
    NSLog(@"text:%@", text);
    NSLog(@"data:%@", data);
    NSLog(@"link:%@", link);
    NSLog(@"imageUrl:%@", picUrl);
    
    //FBLinkShareParams *param = [[FBLinkShareParams alloc] initWithLink:[NSURL URLWithString:link] name:title caption:text description:data picture:[NSURL URLWithString:picUrl]];
    FBLinkShareParams *linkShareParams = [[FBLinkShareParams alloc] init];
    linkShareParams.link = [NSURL URLWithString:link];
    linkShareParams.name = title;
    linkShareParams.caption = text;
    linkShareParams.linkDescription = data;
    linkShareParams.picture = [NSURL URLWithString:picUrl];
    if ([FBDialogs canPresentMessageDialogWithParams:linkShareParams])
    {
        [FBDialogs presentMessageDialogWithParams:linkShareParams clientState:nil handler:^(FBAppCall *call, NSDictionary *results, NSError *error) {
            if (error) {
                NSLog(@"%@", error.description);
            }else{
                NSLog(@"shared success");
            }
        }];
    }
    else
    {
        NSLog(@"can`t shared info...");
        NSMutableDictionary *shareParams = [[NSMutableDictionary alloc] init];
        [shareParams setObject:link forKey:@"link"];
        [shareParams setObject:title forKey:@"name"];
        [shareParams setObject:text forKey:@"caption"];
        [shareParams setObject:data forKey:@"description"];
        [shareParams setObject:picUrl forKey:@"picture"];
        [FBWebDialogs presentFeedDialogModallyWithSession:nil parameters:shareParams handler:^(FBWebDialogResult result, NSURL *resultURL, NSError *error) {
            if (error) {
                NSLog(@"%@", error.description);
            }else{
                if (result == FBWebDialogResultDialogNotCompleted) {
                   
                } else {
                    // Handle the publish feed callback
                    NSLog(@"[resultURL query]--:%@", [resultURL query]);
                    if (![[resultURL query] containsString:@"post_id"]) {
                        
                    } else {
                        // User clicked the Share button
                                            }
                }
            }
        }];
        
    }

另外,非弹窗的分享:

//不显示界面,直接发布到自己的facebook主页上
 
    void MTChannelHelp::facebookPublish(string message, string tags, string link, string picture, string name, string caption, string description) {
         
        NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
         
        if (!message.empty())
            [params setObject:[NSString stringWithUTF8String:message.c_str()] forKey:@"message"];
         
        if (!tags.empty())
            [params setObject:[NSString stringWithUTF8String:tags.c_str()] forKey:@"tags"];
         
        if (!link.empty())
            [params setObject:[NSString stringWithUTF8String:link.c_str()] forKey:@"link"];
         
        if (!picture.empty())
            [params setObject:[NSString stringWithUTF8String:picture.c_str()] forKey:@"picture"];
         
        if (!name.empty())
            [params setObject:[NSString stringWithUTF8String:name.c_str()] forKey:@"name"];
         
        if (!caption.empty())
            [params setObject:[NSString stringWithUTF8String:caption.c_str()] forKey:@"caption"];
         
        if (!description.empty())
            [params setObject:[NSString stringWithUTF8String:description.c_str()] forKey:@"description"];
         
         
        if (![FBSession.activeSession hasGranted:@"publish_actions"]) {
            [FBSession openActiveSessionWithPublishPermissions:[NSArray arrayWithObjects:@"publish_actions", nil]
                                               defaultAudience:FBSessionDefaultAudienceFriends
                                                  allowLoginUI:YES
                                             completionHandler:^(FBSession *session, FBSessionState status, NSError *error) {
             
                                                 if (!error) {
                                                    _facebookPublish(params);
                                                      
                                                 }
                                                 else{
                                                     _facebookGetPermissionsCallback("publish_actions", [error code], [error.localizedDescription UTF8String]);
                                                 }
                                             }];
        }
        else {
            _facebookPublish(params);
        }
    }
     
    void MTChannelHelp::_facebookPublish(void *parameters) {
         
        NSMutableDictionary *params = (NSMutableDictionary *)parameters;
         
        [FBRequestConnection startWithGraphPath:@"/me/feed"
                                     parameters:params
                                     HTTPMethod:@"POST"
                              completionHandler:^(FBRequestConnection *connection,id result,NSError *error) {
                                  if (!error) {
                                      NSString *resultID = [result objectForKey:@"id"];
                                       
                                      LuaValueDict luaDict;
                                      luaDict["success"] = LuaValue::booleanValue(true);
                                      luaDict["postID"] = LuaValue::stringValue([resultID UTF8String]);
                                       
                                      _facebookCallback(FACEBOOK_KEY_PUBLISH, luaDict);
                                  }
                                  else {
                                       
                                      LuaValueDict luaDict;
                                      luaDict["success"] = LuaValue::booleanValue(false);
                                      luaDict["errorCode"] = LuaValue::intValue([error code]);
                                      luaDict["errorInfo"] = LuaValue::stringValue([error.localizedDescription UTF8String]);
                                       
                                      _facebookCallback(FACEBOOK_KEY_PUBLISH, luaDict);
                                  }
                              }];
         
        [params release];
          
    }

转载于:https://my.oschina.net/zhaolu0607/blog/663683

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值