使用 Facebook 登录 iOS
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12740509/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Login with Facebook for iOS
提问by iMash
I have application that is already running on iOS 5 as well as iOS 6. Now for next step I want to implement functionality of "Login with Facebook".
我有已经在 iOS 5 和 iOS 6 上运行的应用程序。现在下一步我想实现“使用 Facebook 登录”的功能。
My application already has login authentication so the facebook login will be additional one.I knew that iOS 6 has provided new framework for facebook but I have two questions:
我的应用程序已经有登录身份验证,所以 facebook 登录将是额外的。 我知道 iOS 6 为 facebook 提供了新的框架,但我有两个问题:
- How do I implement this facebook functionality, so that it should work on both iOS 5 and iOS 6 devices? 2.How do I maintain session with facebook login?
- 我如何实现这个 facebook 功能,以便它可以在 iOS 5 和 iOS 6 设备上运行?2.如何与facebook登录保持会话?
回答by barryjones
1) Follow these steps for facebook login instructions: https://developers.facebook.com/docs/howtos/login-with-facebook-using-ios-sdk/
1) 按照以下步骤获取 facebook 登录说明:https: //developers.facebook.com/docs/howtos/login-with-facebook-using-ios-sdk/
2) Once you implement the above using facebook sdk 3.x, this will also work for iOS 5 and iOS 6.
2) 一旦您使用 facebook sdk 3.x 实现了上述内容,这也适用于 iOS 5 和 iOS 6。
回答by Shaik Riyaz
1.To support login in ios 5 and ios 6 , you can use FBLoginView Class . it is the simplest way to login into facebook using Facebook sdk .
1.支持ios 5和ios 6登录,可以使用FBLoginView类。这是使用 Facebook sdk 登录 facebook 的最简单方法。
FBLoginView * pFBLoginViewObj = [[FBLoginView alloc] init];
[pFBLoginViewObj setFrame:self.view.frame];
pFBLoginViewObj.delegate = self;//optional
[self.view addSubview:pFBLoginViewObj];
implement delegate methods if needed .
如果需要,实现委托方法。
2.To maintain session you have to make changes in app dalagate file ....like
2.要保持会话,您必须在应用程序 dalagate 文件中进行更改....like
-(BOOL) application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
if (url != nil)
{
return [[FBSession activeSession] handleOpenURL:url];
}
return NO;
}
- (void)applicationDidBecomeActive:(UIApplication *)application
{
[[FBSession activeSession] handleDidBecomeActive];
}
- (void)applicationWillTerminate:(UIApplication *)application
{
[[FBSession activeSession] close];
}
回答by User558
First of all we have to add this frameworks in our projects,
首先我们必须在我们的项目中添加这个框架,
after that you can import this methods in appDelegate
之后,您可以在 appDelegate 中导入此方法
#import <FacebookSDK/FacebookSDK.h>
#import <FBSDKCoreKit/FBSDKCoreKit.h>
after that didFinishLaunchingWithOptions we have to add this method
在 didFinishLaunchingWithOptions 之后我们必须添加这个方法
[[FBSDKApplicationDelegate sharedInstance] application:application
didFinishLaunchingWithOptions:launchOptions];
you can call Callback Methods,
你可以调用回调方法,
#pragma mark - Callback methods
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
return [[FBSDKApplicationDelegate sharedInstance] application:application openURL:url sourceApplication:sourceApplication annotation:annotation];
}
after that in your facebooklogin action method we have to write,
之后,在您的 facebooklogin 操作方法中,我们必须编写,
FBSDKLoginManager *loginManager = [[FBSDKLoginManager alloc] init];
[loginManager logInWithReadPermissions:@[@"public_profile", @"email"] fromViewController:self handler:^(FBSDKLoginManagerLoginResult *result, NSError *error) {
//TODO: process error or result.
if (error) {
NSLog(@"Process error");
[self facebookLoginFailed:YES];
} else if (result.isCancelled) {
[self facebookLoginFailed:NO];
} else {
if ([FBSDKAccessToken currentAccessToken]) {
NSLog(@"Token is available : %@",[[FBSDKAccessToken currentAccessToken]tokenString]);
NSMutableDictionary* parameters = [NSMutableDictionary dictionary];
[parameters setValue:@"id,name,email,first_name,last_name,picture.type(large)" forKey:@"fields"];
[[[FBSDKGraphRequest alloc] initWithGraphPath:@"me" parameters:parameters]
startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
if (!error) {
NSString *fbPhotoUrl = [[[result objectForKey:@"picture"]objectForKey:@"data"]objectForKey:@"url"];
lDefaults = [NSUserDefaults standardUserDefaults];
[lDefaults setObject:@"fbPhotoUrl" forKey:@"fbPhotoUrl"];
[lDefaults synchronize];
NSLog(@"%@",fbPhotoUrl);
}
}];
}
else {
[self facebookLoginFailed:YES];
}
}
}];
if facebook login failed we can write this alert,
如果 facebook 登录失败,我们可以写这个警报,
- (void)facebookLoginFailed:(BOOL)isFBResponce{
if(isFBResponce){
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:NSLocalizedString(@"pop_attention", nil) message:NSLocalizedString(@"request_error", nil) delegate:self cancelButtonTitle:NSLocalizedString(@"pop_ok", nil) otherButtonTitles: nil];
[alert show];
}
else{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:NSLocalizedString(@"pop_attention", nil) message:NSLocalizedString(@"loginfb_cancelled", nil) delegate:self cancelButtonTitle:NSLocalizedString(@"pop_ok", nil) otherButtonTitles: nil];
[alert show];
}
}
after that goto target-->info-->Url Types-->UrlSchmes(add your facebook id).
之后转到目标--> 信息--> Url 类型--> UrlSchmes(添加您的 facebook id)。
and more thing we have to do in www.developers.facebook.com go to ypur app-->under AppReview-->Make YourApp public? as YES.
还有更多我们必须在 www.developers.facebook.com 上做的事情,请转到 ypur 应用程序--> 在 AppReview 下--> 将您的应用程序设为公开?是的。
after that we need to add tis code in plist
之后我们需要在plist中添加tis代码
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleURLSchemes</key>
<array>
<string>fb1801381186770425</string>
</array>
</dict>
</array>
<key>FacebookAppID</key>
<string>AddYourID</string>
<key>FacebookDisplayName</key>
<string>YourAppName</string>
<key>LSApplicationQueriesSchemes</key>
<array>
<string>fbapi</string>
<string>fb-messenger-api</string>
<string>fbauth2</string>
<string>fbshareextension</string>
<string>instagram</string>
</array>
<key>NSLocationWhenInUseUsageDescription</key>
<string>To access your current location</string>
<key>NSPhotoLibraryUsageDescription</key>
<string>To share </string>
that's it in Objective-C.
在Objective-C中就是这样。
In SwiftVersion
在Swift版本中
In appdelegate method we need to import this frameworks
在 appdelegate 方法中,我们需要导入这个框架
import FacebookCore
import FacebookLogin
import FBSDKLoginKit
after that in didFinishLaunchingWithOptions write
之后在 didFinishLaunchingWithOptions 中写入
FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions)
and call callback method
并调用回调方法
func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
return FBSDKApplicationDelegate.sharedInstance().application(application, open: url as URL!, sourceApplication: sourceApplication, annotation: annotation)
}
after that in your viewcontroller import same frameworks after that write thiese lines of code in your facebook login action
之后在您的视图控制器中导入相同的框架,然后在您的 facebook 登录操作中编写这些代码行
var dict : [String : AnyObject]!
let fbLoginManager : FBSDKLoginManager = FBSDKLoginManager()
fbLoginManager.logIn(withReadPermissions: ["email"], from: self) { (result, error) in
if (error == nil){
let fbloginresult : FBSDKLoginManagerLoginResult = result!
if fbloginresult.grantedPermissions != nil {
if(fbloginresult.grantedPermissions.contains("email")) {
self.getFBUserData()
}
}
}
}
after that i am getting user data and storing in Dictionary
之后我正在获取用户数据并存储在字典中
func getFBUserData(){
if((FBSDKAccessToken.current()) != nil){
FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id, name, first_name, last_name, picture.type(large), email"]).start(completionHandler: { (connection, result, error) -> Void in
if (error == nil){
self.dict = result as! [String : AnyObject]
print(result!)
print(self.dict)
}
})
}
}
回答by Usman
https://developers.facebook.com/features/whats-new-ios-sdk-3.1/
https://developers.facebook.com/features/whats-new-ios-sdk-3.1/
Take a look at this Facebook sdk work for both iOS5 and iOS6 as well.
看看这个 Facebook sdk 也适用于 iOS5 和 iOS6。