ios - Facebook 登录无法快速工作

标签 ios swift facebook facebook-ios-sdk

我试图在我的应用程序中实现 Facebook 登录,但当我尝试登录时,它会转到 Facebook 应用程序并返回我的游戏,但登录按钮不会变为注销,如果我尝试获取任何信息,例如访问权限 token 、授予的权限或拒绝的权限为零。这是我的代码:

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>

最佳答案

感谢这篇文章: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

  • 在应用程序中添加委托(delegate):

    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 中我显示按钮(也可以在 View Controller 中):

    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)
            }
         })
         }
    
    }
    

关于ios - Facebook 登录无法快速工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39970855/

相关文章:

facebook - 如何检查给定的用户 ID 是否已验证我的应用程序?

ios - Xamarin 表单 IOS 项目调试不工作

ios - TableViewCell 和 TableViewController 中 UIStepper 的委托(delegate)错误

ios - Ngbdropdown 单击事件不适用于 ios phonegap,角度 8 运行 cordova

c# - 尝试制作动画时,C# 中的完成处理程序是什么样的?

swift - 如何使用静默推送通知按需更新用户位置? iOS

ios - 使用自动布局嵌入单个 View 中的两个 UITableView 的动态高度

mysql - 将模型对象链接到 Vapor 中的现有数据库表

android - Facebook 原生广告 - 原生广告加载失败 : No fill

android - 用户在 Facebook 上分享时,Google Play 应用列表显示为 "Not Found"