Facebook接入
1.1官方文档
2.1 在配置文件Info.plist中配置应用白名单,必须添加以下所有字段,否则可能无法跳转
<key>LSApplicationQueriesSchemes</key>
<array>
<string>fbapi</string>
<string>fb-messenger-api</string>
<string>fbauth2</string>
<string>fbshareextension</string>
</array>
2.2点击XCode项目名,选择Info,添加FaceBook的URL Types
identifier:fb URL Schemes:fb前缀后+FaceBook App ID(用户自己申请的账号)
2.3 Appdelegate中的配置
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
//facebook
[[FBSDKApplicationDelegate sharedInstance] application:application didFinishLaunchingWithOptions:launchOptions];
[FBSDKSettings setAppID:Facebook_APP_ID];
return YES;
}
// 2
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation{
return
[[FBSDKApplicationDelegate sharedInstance] application:application openURL:url sourceApplication:sourceApplication annotation:annotation]
}
// 3
- (void)applicationDidBecomeActive:(UIApplication *)application {
[FBSDKAppEvents activateApp];
}
2.4 loginFacebook方法
- (void)loginFacebookSuccess:(UIViewController *)viewController success:(void (^)(id response))successBlock failure:(void (^)(NSError *error))failureBlock{
FBSDKLoginManager *login = [[FBSDKLoginManager alloc] init];
[login logOut];
[[FBSDKLoginManager new] logOut];
//这个一定要写,不然会出现换一个帐号就无法获取信息的错误(退出方法)
[FBSDKProfile enableUpdatesOnAccessTokenChange:YES];
login.loginBehavior = FBSDKLoginBehaviorBrowser; // 优先客户端方式
[login logInWithReadPermissions: @[@"public_profile"]
fromViewController:viewController
handler:^(FBSDKLoginManagerLoginResult *result, NSError *error) {
if (error) {
NSError *error = [CIAccountError createError:ErrorThirdLoginFailure];
failureBlock(error);
} else if (result.isCancelled) {
NSError *error = [CIAccountError createError:ErrorThirdLoginCancel];
failureBlock(error);
} else {
NSString *token = result.token.tokenString;
FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc]
initWithGraphPath:result.token.userID
parameters:nil
HTTPMethod:@"GET"];
[request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection,
id result,
NSError *error) {
if (error) {
NSError *resultError = [CIAccountError createError:ErrorThirdLoginFailure];
failureBlock(resultError);
}else{
NSString *nickName = [result objectForKey:@"name"];
NSString *openId = [result objectForKey:@"id"];
NSDictionary *resultDic = @{@"openid":openId,
@"nickname":nickName,
@"account_type":@"facebook",
@"access_token":token,
@"third_appid":Facebook_APP_ID};
successBlock(resultDic);
}
}];
}
}];
}