2016-10-11 89 views
0

我试图在我的应用中实现Facebook登录,但是当我尝试登录时,它会转到Facebook应用并返回到我的游戏,但登录按钮不会退出,如果我尝试获取访问令牌,授予的权限或拒绝的权限等任何信息。这是我的代码有:Facebook登录不能在swift中工作

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> 

+0

你使用哪个版本迅速? –

+0

不够好给你一个完整的解决方案,所以这就是它。试试看,https://edbinx.com/apple/ios/use-facebook-fbsdk-swift-cocoapods-ios-9-13369.html – Fennec

+0

即时通讯使用Swift 3 @HimanshuMoradiya – toiavalle

回答

3

多亏了这个帖子: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) 
    } 
    
    我在显示按钮(也可以在视图控制器中):(
    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) 
         } 
        }) 
        } 
    
    } 
    
1

将这个代码在你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 Facebook按钮中的FacebookAccessToken点击ViewController。

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) 

     } 
    }) 
} 
+0

我已经拥有App Delegate代码(抱歉,我忘记了包含在问题中)。对于中间部分,我应该把代码放在哪里?我需要一个视图控制器还是可以使用SKScene Im?我应该在哪里放? viewDidLoad中?当我尝试添加它时,也出现此错误无法将类型'(FBSDKLoginManagerLoginResult !, NSError!) - > Void'的值转换为期望的参数类型'FBSDKLoginManagerRequestTokenHandler!' – toiavalle

+0

@toiavalle我不使用swift 3.0我使用的是swift 2.0,所以他们可能从你的身边,然后将此代码转换为swift 3.0中的正常工作。谢谢。 –