Facebook登录无法快速工作
Posted
技术标签:
【中文标题】Facebook登录无法快速工作【英文标题】:Facebook login not working in swift 【发布时间】:2016-10-11 05:10:59 【问题描述】:我正在尝试在我的应用中实现 Facebook 登录,但当我尝试登录时,它会转到 Facebook 应用并返回我的游戏,但登录按钮不会变为注销,并且如果我尝试获取任何信息,例如访问权限令牌,授予权限或拒绝权限它是零。这是我的代码:
import Foundation
class IntroScene: SKScene, FBSDKLoginButtonDelegate
let loginButton: FBSDKLoginButton =
let button = FBSDKLoginButton()
button.readPermissions = ["email"]
return button
()
override func didMove(to view: SKView)
self.backgroundColor = UIColor.black
view.addSubview(loginButton)
loginButton.center = (self.view?.center)!
loginButton.delegate = self
func loginButtonDidLogOut(_ loginButton: FBSDKLoginButton!)
func loginButtonWillLogin(loginButton: FBSDKLoginButton!) -> Bool
return true
func loginButton(_ loginButton: FBSDKLoginButton!, didCompleteWith result: FBSDKLoginManagerLoginResult!, error: Error!)
if(error == nil)
print("login complete")
//print(FBSDKAccessToken.current()) -> crashes because its nil
//print(result.grantedPermissions) -> crashes its nil
else
print(error.localizedDescription)
我的 info.plist 如下所示:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>UIViewControllerBasedStatusBarAppearance</key>
<false/>
<key>LSApplicationQueriesSchemes</key>
<array>
<string>fbapi</string>
<string>fb-messenger-api</string>
<string>fbauth2</string>
<string>fbshareextension</string>
</array>
<key>NSAppTransportSecurity</key>
<dict>
<key>NSExceptionDomains</key>
<dict>
<key>facebook.com</key>
<dict>
<key>NSIncludesSubdomains</key>
<true/>
<key>NSThirdPartyExceptionRequiresForwardSecrecy</key>
<false/>
</dict>
<key>fbcdn.net</key>
<dict>
<key>NSIncludesSubdomains</key>
<true/>
<key>NSThirdPartyExceptionRequiresForwardSecrecy</key>
<false/>
</dict>
<key>akamaihd.net</key>
<dict>
<key>NSIncludesSubdomains</key>
<true/>
<key>NSThirdPartyExceptionRequiresForwardSecrecy</key>
<false/>
</dict>
</dict>
</dict>
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleURLSchemes</key>
<array>
<string>//fbmyid</string>
</array>
</dict>
</array>
<key>FacebookAppID</key>
<string>//myid</string>
<key>FacebookDisplayName</key>
<string>Crazy Traffic Saga</string>
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>1</string>
<key>LSRequiresIPhoneOS</key>
<true/>
<key>UILaunchStoryboardName</key>
<string>LaunchScreen</string>
<key>UIMainStoryboardFile</key>
<string>Main</string>
<key>UIRequiredDeviceCapabilities</key>
<array>
<string>armv7</string>
</array>
<key>UISupportedInterfaceOrientations</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
<key>UISupportedInterfaceOrientations~ipad</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationPortraitUpsideDown</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
【问题讨论】:
您使用哪个 swift 版本? 不够好,无法为您提供完整的解决方案,所以在这里。试试看,edbinx.com/apple/ios/… 我正在使用 Swift 3 @HimanshuMoradiya 我基本上在做本教程的第一部分,但无法让它工作@Fennec 【参考方案1】:感谢这篇文章:FB Login using Swift 3 not returning any values and not get back the user to the App after successful login 我发现了问题。还有一个功能应该添加到 App Delegate 中。 这是我如何让 Facebook 登录工作
下载SDK并添加到项目中
根据Facebook网站设置info.plist
在应用程序中添加了委托:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool
// Override point for customization after application launch.
FIRApp.configure()
FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions)
return true
public func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool
return FBSDKApplicationDelegate.sharedInstance().application(
app,
open: url as URL!,
sourceApplication: options[UIApplicationOpenURLOptionsKey.sourceApplication] as! String,
annotation: options[UIApplicationOpenURLOptionsKey.annotation]
)
public 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)
在 SKScene 中,我正在显示按钮(也可以在视图控制器中):
class IntroScene: SKScene, FBSDKLoginButtonDelegate
override func didMove(to view: SKView)
self.backgroundColor = UIColor.black
let loginButton = FBSDKLoginButton()
loginButton.center = (self.view?.center)!
self.view?.addSubview(loginButton)
loginButton.frame = CGRect(x: 0, y: 0, width: 360, height: 60) // makes it bigger
loginButton.center = CGPoint(x: self.frame.midX, y: self.frame.midY + 90)
loginButton.delegate = self
loginButton.readPermissions = ["public_profile", "email"]
if let _ = FBSDKAccessToken.current()
//already logged in
fetchProfile()
func fetchProfile()
let parameters = ["fields": "first_name, email, last_name, picture"]
FBSDKGraphRequest(graphpath: "me", parameters: parameters).start(completionHandler: (connection, user, requestError) -> Void in
if requestError != nil
print("----------ERROR-----------")
print(requestError)
return
let userData = user as! NSDictionary
let email = userData["email"] as? String
let firstName = userData["first_name"] as? String
let lastName = userData["last_name"] as? String
var pictureUrl = ""
if let picture = userData["picture"] as? NSDictionary, let data = picture["data"] as? NSDictionary, let url = data["url"] as? String
pictureUrl = url
print(pictureUrl)
)
【讨论】:
【参考方案2】:将此代码放入您的 AppDelegate.swift
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool
return FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions)
func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject) -> Bool
return FBSDKApplicationDelegate.sharedInstance().application(application, openURL: url, sourceApplication: sourceApplication, annotation: annotation)
在您的 Facebook Button Click ViewController 中检查 FacebookAccessToken。
if FBSDKAccessToken.currentAccessToken() != nil
FBSDKLoginManager().logOut()
return
let login:FBSDKLoginManager = FBSDKLoginManager()
login.logInWithReadPermissions(["email"], handler: (result:FBSDKLoginManagerLoginResult!, error:NSError!) -> Void in
if(error != nil)
FBSDKLoginManager().logOut()
else if(result.isCancelled)
FBSDKLoginManager().logOut()
else
//Handle login success
self.returnUserData()
)
获取 FacebookData 的响应。
func returnUserData()
let graphRequest : FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "email"])
graphRequest.startWithCompletionHandler( (connection, result, error) -> Void in
if ((error) != nil)
// Process error
print("Error: \(error)")
else
print(result)
)
【讨论】:
我已经有了 App Delegate 代码(抱歉,我忘了在问题中包含)。对于中间部分,我应该把代码放在哪里?我需要一个视图控制器还是可以使用我正在使用的 SKScene?我应该把它放在哪里?视图加载?当我尝试添加它时,我也收到此错误无法将类型“(FBSDKLoginManagerLoginResult!,NSError!)-> Void”的值转换为预期的参数类型“FBSDKLoginManagerRequestTokenHandler!” @toiavalle 我不使用 swift 3.0 我正在使用 swift 2.0,所以他们可能从你身边然后转换此代码以便在 swift 3.0 中正常工作。谢谢。【参考方案3】:现在 Facebook 为您的 iOS 应用程序提供 Swift sdk。 Swift sdk for Facebook
检查一下,玩得开心
【讨论】:
【参考方案4】:不要忘记设置 Keychain Sharing 项目目标 -> Capabilities -> Keychain Sharing -> Toggle Switch ON Keychain Sharing status
你可以关注这个http://ashishkakkad.com/2015/05/facebook-login-swift-language-ios/
【讨论】:
以上是关于Facebook登录无法快速工作的主要内容,如果未能解决你的问题,请参考以下文章