Facebook SDK 使用 Swift 3 iOS 10 登录
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39899327/
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
Facebook SDK sign in with Swift 3 iOS 10
提问by robertbabington
I installed Facebook's Swift SDK via Cocoapods:
我通过 Cocoapods 安装了 Facebook 的 Swift SDK:
pod 'FacebookCore', :git => "https://github.com/facebook/facebook-sdk-swift"
pod 'FacebookLogin', :git => "https://github.com/facebook/facebook-sdk-swift"
I have followed the login instructions from Facebook's Swift SDK (https://developers.facebook.com/docs/swift/login) but cannot get it working.
我已按照 Facebook 的 Swift SDK ( https://developers.facebook.com/docs/swift/login) 中的登录说明进行操作,但无法使其正常工作。
Inside my view controller I have the following:
在我的视图控制器中,我有以下内容:
@objc fileprivate func facebookSignIn() {
let loginManager = LoginManager()
print("LOGIN MANAGER: \(loginManager)")
loginManager.logIn([ .publicProfile, .email ], viewController: self) { loginResult in
print("LOGIN RESULT! \(loginResult)")
switch loginResult {
case .failed(let error):
print("FACEBOOK LOGIN FAILED: \(error)")
case .cancelled:
print("User cancelled login.")
case .success(let grantedPermissions, let declinedPermissions, let accessToken):
print("Logged in!")
print("GRANTED PERMISSIONS: \(grantedPermissions)")
print("DECLINED PERMISSIONS: \(declinedPermissions)")
print("ACCESS TOKEN \(accessToken)")
}
}
}
"Login manager: etc." prints when I click the button and the web view opens. I can sign in via Facebook and then the web view goes blank and nothing happens. The app shows in my Facebook apps, so some authorisation has taken place, but if I click the "Done" button in the web view, the result to the callback is .cancelled
and "User cancelled login." is printed.
“登录管理器:等” 当我单击按钮并打开 Web 视图时打印。我可以通过 Facebook 登录,然后网络视图变为空白,什么也没有发生。该应用程序显示在我的 Facebook 应用程序中,因此已经进行了一些授权,但是如果我单击 Web 视图中的“完成”按钮,回调的结果是.cancelled
“用户取消登录”。被打印。
I have added Keychain Sharing to my entitlements, and I've updated my info.plist:
我已将钥匙串共享添加到我的权利中,并更新了我的 info.plist:
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleURLSchemes</key>
<array>
<string> [ FB STRING ] </string>
</array>
</dict>
</array>
<key>FacebookAppID</key>
<string>[ APP ID ]</string>
<key>FacebookDisplayName</key>
<string>[ APP NAME ]</string>
<key>LSApplicationQueriesSchemes</key>
<array>
<string>fbapi</string>
<string>fb-messenger-api</string>
<string>fbauth2</string>
<string>fbshareextension</string>
</array>
I've even changed my NSAppTransportSecurity
settings.
我什至改变了我的NSAppTransportSecurity
设置。
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
I know this is a duplicate of iOS 9 Facebook login simulator -canOpenURL: failed for URL: "fbauth2:///" - error: "(null)"and How to use Facebook iOS SDK on iOS 10but none of the solutions there seem to work for me, unless I've missed something? Any suggestions are appreciated.
我知道这是iOS 9 Facebook 登录模拟器的副本 -canOpenURL: failed for URL: "fbauth2:///" - error: "(null)"和How to use Facebook iOS SDK on iOS 10但没有任何解决方案似乎对我有用,除非我错过了什么?任何建议表示赞赏。
Several errors are printed also:
还打印了几个错误:
[App] if we're in the real pre-commit handler we can't actually add any new fences due to CA restriction
[error] error: (6922) I/O error for database at /var/mobile/Containers/Data/Application/F3D8E126-B0CC-4C06-81A5-D7A7F849B3BD/Documents/OfflineModel2.sqlite. SQLite error code:6922, 'disk I/O error'
And when I don't have the FB app installed on my device, I get:
当我的设备上没有安装 FB 应用程序时,我得到:
-canOpenURL: failed for URL: "fbauth2:/" - error: "The operation couldn't be completed. (OSStatus error -10814.)"
回答by Wilson
You have to substitute didfinishlaunching and openurl AppDelegate methods with below:
您必须用以下方法替换 didfinishlaunching 和 openurl AppDelegate 方法:
public func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool
{
return SDKApplicationDelegate.shared.application(application, didFinishLaunchingWithOptions: launchOptions)
}
public func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool
{
return SDKApplicationDelegate.shared.application(app, open: url, options: options)
}
回答by Pan Mluv?í
Swift 3and Swift 4
斯威夫特 3和斯威夫特 4
add this to your AppDelegate.swift
将此添加到您的 AppDelegate.swift
import FBSDKCoreKit
import FBSDKLoginKit
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
return FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions)
}
func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
return FBSDKApplicationDelegate.sharedInstance().application(app, open: url, options: options)
}
回答by Thomas Oropeza
The FBSDK Libraries are deprecated. The newer libraries can be found in Facebook's Github repository.
不推荐使用 FBSDK 库。较新的库可以在Facebook 的 Github 存储库中找到。
For this particular error, implement the following application methods.
对于此特定错误,请实施以下应用程序方法。
func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
return SDKApplicationDelegate.shared.application(application, open: url, sourceApplication: sourceApplication, annotation: annotation)
}
func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
return SDKApplicationDelegate.shared.application(app, open: url, options: options)
}
回答by David Sanford
Swift 3.0
斯威夫特 3.0
on your AppDelete.swift:
在你的 AppDelete.swift 上:
import FBSDKCoreKit
import FBSDKLoginKit
inside your:
在您的:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool
{
add:
添加:
FBSDKApplicationDelegate .sharedInstance() .application(application, didFinishLaunchingWithOptions: launchOptions)
then create a new func as follows:
然后创建一个新的 func 如下:
func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
return FBSDKApplicationDelegate.sharedInstance().application(app, open: url, options: options)
}
回答by User558
Using Cocoapodsin Swift 3.0
在Swift 3.0 中使用Cocoapods
Install cocoapods
安装 cocoapods
pod 'FacebookCore'
pod 'FacebookLogin'
in AppDelegate.swift
在 AppDelegate.swift 中
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions)
}
and writedown Callback method
和 writedown 回调方法
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)return FBSDKApplicationDelegate.sharedInstance().application(application, open: url as URL!, sourceApplication: sourceApplication, annotation: annotation)
}
in your viewController
在您的视图控制器中
import FacebookCore
import FacebookLogin
import FBSDKLoginKit
after that in your fblogin button write down this code
之后在你的 fblogin 按钮中写下这段代码
@IBAction func faceBookLoginBtnAction(_ sender: Any) {
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")) {
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)
}
})
}
}
}
}
}
}
and one more important thing add your facebookid into your project In the Project > Target > Info > URL Types section, set the proper Facebook ID and to the URL Schemes.
还有一件更重要的事情是将您的 facebookid 添加到您的项目中 在 Project > Target > Info > URL Types 部分中,设置正确的 Facebook ID 和 URL Schemes。
回答by Mahendra
First thing you need to create an application to use Facebook login in your application. You can create an app on facebook from here
首先,您需要创建一个应用程序以在您的应用程序中使用 Facebook 登录。您可以从这里在 facebook 上创建一个应用程序
You need to set URL types
, FacebookAppID
, FacebookDisplayName
and LSApplicationQueriesSchemes
into your info.plist
.
您需要设置URL types
,FacebookAppID
,FacebookDisplayName
和LSApplicationQueriesSchemes
到您info.plist
。
Manually add the Facebook login framework or you can use cocoa pods as follows...
pod 'FacebookCore' //latest one pod 'FacebookLogin' // for fb login pod 'FacebookShare' //for sharing on fb
and then
pod install
command to install pods for your application.import FacebookCore
in your application delegate to use Facebook loginSet up following things in
AppDelegate.swift
file:func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { return SDKApplicationDelegate.shared.application(application, didFinishLaunchingWithOptions: launchOptions) } func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool { if url.absoluteString.contains(<Your FBAppID>) { return SDKApplicationDelegate.shared.application(app, open: url, options: options) } else { debugPrint("Error in openURL from AppDelegate Facebook Sign in") } return true }
手动添加 Facebook 登录框架,或者您可以使用可可豆荚,如下所示...
pod 'FacebookCore' //latest one pod 'FacebookLogin' // for fb login pod 'FacebookShare' //for sharing on fb
然后
pod install
命令为您的应用程序安装 pod。import FacebookCore
在您的应用程序委托中使用 Facebook 登录在
AppDelegate.swift
文件中设置以下内容:func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { return SDKApplicationDelegate.shared.application(application, didFinishLaunchingWithOptions: launchOptions) } func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool { if url.absoluteString.contains(<Your FBAppID>) { return SDKApplicationDelegate.shared.application(app, open: url, options: options) } else { debugPrint("Error in openURL from AppDelegate Facebook Sign in") } return true }
And now you are successfully configured Facebook login into your app.
现在您已成功配置 Facebook 登录到您的应用程序。
In your view controller, you need to do the following:
在您的视图控制器中,您需要执行以下操作:
import FacebookLoginKit
In your IBAction Method do the following:
在您的 IBAction 方法中执行以下操作:
@IBAction func btnFacebookSignInTapped(_ sender: UIButton) {
let fbManager = FBSDKLoginManager()
fbManager.logIn(withReadPermissions: ["public_profile", "email"], from: self) { (result, error) in
if let loginResult = result, error == nil {
if let permissions = loginResult.grantedPermissions {
if permissions.contains("email") || permissions.contains("public_profile") {
if FBSDKAccessToken.current() != nil {
FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id, name, first_name, last_name, email"]).start(completionHandler: { (connection, graphResult, error) in
if error == nil {
debugPrint("Result: \(graphResult!)")
if let data = graphResult as? [String: Any] {
print("User details from FB: \(data)")
}
}
})
} else {
print("Invalid FB access token");
}
}
} else {
print("Fail to login using facebook.")
}
} else {
print("Error in facebook login")
}
}
}
By doing so you will be able to login to Facebook.
通过这样做,您将能够登录 Facebook。
回答by David Ta
Other way to do it. Hope this video be helpfull for you https://youtu.be/bOS4jqRc8Io
其他方法来做到这一点。希望这个视频对你有帮助 https://youtu.be/bOS4jqRc8Io
Contents in this Video: Facebook SDK integration tutorial with Swift lastest 2018 Xcode new project setup Swift iOS app login with Facebook Tutorial Facebook login feature in iOS app Add Facebook to Swift iOS app Facebook login in iOS app
此视频中的内容: Facebook SDK 集成教程与 Swift 最新 2018 Xcode 新项目设置 Swift iOS 应用程序登录与 Facebook 教程 iOS 应用程序中的 Facebook 登录功能将 Facebook 添加到 Swift iOS 应用程序 Facebook 登录 iOS 应用程序
Steps: 1. Create new simple Swift Xcode project 2- Login to facebook develop page to create the same name APP 3- Add login with Facebook button, login and logout methods 4- Modify the configure plist, create bridging header for C, configure AppDelegate, 5- Run the application and test with simulator
步骤: 1.新建一个简单的Swift Xcode项目 2-登录facebook开发页面创建同名APP 3-添加使用Facebook登录的按钮,登录和注销方法 4-修改配置plist,为C创建桥接头,配置AppDelegate , 5- 运行应用程序并使用模拟器进行测试
回答by Kiran jadhav
updated for swift 3 :
为 swift 3 更新:
// In your AppDelegate() :
// 在你的 AppDelegate() 中:
// Step - 1:
// 第1步:
import FacebookCore
//Step - 2: In didFinishLaunchingWithOptions()
//步骤 - 2:在 didFinishLaunchingWithOptions() 中
// FB Settings
SDKApplicationDelegate.shared.application(application, didFinishLaunchingWithOptions: launchOptions)
// Instance Method():
// 实例方法():
func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
print("URL AbsoluteString = \(url.absoluteString)")
if url.absoluteString.contains("fb1279300242197274") {
return SDKApplicationDelegate.shared.application(app,
open: url,
options: options)
}
else {
//return PDKClient.sharedInstance().handleCallbackURL(url)
print("Error while open URL from app delegate facebook sign in")
}
return true
}
回答by Milan Nosá?
Answers here recommend using following implementation of application(_,didFinishLaunchingWithOptions:)
:
此处的答案建议使用以下实现application(_,didFinishLaunchingWithOptions:)
:
public func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {
return SDKApplicationDelegate.shared.application(application, didFinishLaunchingWithOptions: launchOptions)
}
However, note that official documentationdoesn't use the return value of
但是,请注意官方文档不使用返回值
SDKApplicationDelegate.shared.application(application, didFinishLaunchingWithOptions: launchOptions)
as the return value of application(_,didFinishLaunchingWithOptions:)
.
作为 的返回值application(_,didFinishLaunchingWithOptions:)
。
Now while this might seem like unimportant, I've had big problems while integrating facebook SDK with branch deep linking, because exactly this line cause me problems. Therefore, if you want to prevent some unnecessary problems later, use the following solution:
现在虽然这看起来不重要,但我在将 facebook SDK 与分支深度链接集成时遇到了大问题,因为正是这条线给我带来了问题。因此,如果您想防止以后出现一些不必要的问题,请使用以下解决方案:
public func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool
{
SDKApplicationDelegate.shared.application(application, didFinishLaunchingWithOptions: launchOptions)
// always return true
return true
}
public func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool
{
return SDKApplicationDelegate.shared.application(app, open: url, options: options)
}