2017-02-16 4 views
0

基本的に私はfacebookLogin.swiftという名前のクラスと、ログインページと、ViewController.Swiftというホームページを持っています。私はFacebookのログイン情報をすべて正しくコーディングしており、FBSDKが提供するボタンと定義したカスタムボタンの両方でログインしてログアウトすることができます。しかし、私は、ユーザーがログインしている場合ViewController.swiftページに移動する方法を見つけ出すことはできませんユーザーがFacebook経由でログインしている場合、別のviewControllerをプログラムで起動する方法

をここでfacebookLogin.swiftコードは次のとおりです。ここで

import UIKit 
import FBSDKCoreKit 
import FBSDKLoginKit 

class facebookLogin: UIViewController, FBSDKLoginButtonDelegate { 
    var loginStatus = false; 

    @IBOutlet weak var facebookOutlet: UIButton! 

    override func viewDidLoad() { 
     super.viewDidLoad() 
     super.viewDidLoad() 
     let loginButton = FBSDKLoginButton() 
     view.addSubview(loginButton) 
     loginButton.center = view.center 
     loginButton.delegate = self; 
     loginButton.readPermissions = ["email","public_profile"] 
    } 

    @IBAction func facebookAction(_ sender: Any) { 
     customFBLogin() 
     if (FBSDKAccessToken.current() != nil) { 
      NSLog("it works") 
     } 
    } 

    func customFBLogin() { 
     FBSDKLoginManager().logIn(withReadPermissions: ["email","public_profile"], from: self) { (result, err) in 
      if err != nil { 
       print("Facebook Login Error Failed \(err)") 
       return; 
      } 
      self.showEmailAddress(); 
      self.loginStatus = true; 
     } 
    } 



    func loginButtonDidLogOut(_ loginButton: FBSDKLoginButton!) { 
     print("Did log out of Facebook") 
    } 

    func loginButton(_ loginButton: FBSDKLoginButton!, didCompleteWith result: FBSDKLoginManagerLoginResult!, error: Error!) { 
     if error != nil { 
      print(error) 
      return; 
     } else { 
      print("Successfuly logged into Facebook"); 
      showEmailAddress() 

     } 
    } 

    func showEmailAddress() { 
     FBSDKGraphRequest(graphPath: "/me", parameters: ["fields": "id, name, email"]).start(completionHandler: { (connection, result, err) in 

      if err != nil { 
       print("Failed to start graph request \(err)") 
       return; 
      } 
      print(result) 

     }) 
    } 


    override func didReceiveMemoryWarning() { 
     super.didReceiveMemoryWarning() 
     // Dispose of any resources that can be recreated. 
    } 


    /* 
    // MARK: - Navigation 

    // In a storyboard-based application, you will often want to do a little preparation before navigation 
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) { 
     // Get the new view controller using segue.destinationViewController. 
     // Pass the selected object to the new view controller. 
    } 
    */ 

} 

はAppDelegateから関連するコードです.swiftファイル:AppDelegate.swiftクラスの最初のアプリケーション機能で

import UIKit 
import CoreData 
import Firebase 
import FBSDKCoreKit 

@UIApplicationMain 
class AppDelegate: UIResponder, UIApplicationDelegate { 

    var window: UIWindow? 
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { 
     // Override point for customization after application launch. 
     FIRApp.configure() 
     FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions) 

     let mainStoryBoard = UIStoryboard.init(name: "Main", bundle: nil) 
     self.window = UIWindow(frame: UIScreen.main.bounds) 
     var initialViewController: UIViewController 

     if(FBSDKAccessToken.current() != nil) { 
      let vc = mainStoryBoard.instantiateViewController(withIdentifier: "ViewController") as! ViewController 
      initialViewController = vc 
     } else{ 
      initialViewController = mainStoryBoard.instantiateViewController(withIdentifier: "facebookLogin") 
     } 

     self.window?.rootViewController = initialViewController 

     self.window?.makeKeyAndVisible() 

     return true 
    } 

    func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool { 
     let handled = FBSDKApplicationDelegate.sharedInstance().application(app, open: url, sourceApplication: options[UIApplicationOpenURLOptionsKey.sourceApplication] as! String!, annotation: options[UIApplicationOpenURLOptionsKey.annotation]) 

     return handled; 
    } 

、私はこのコードを使うことを提案stackoverflowの上の別のチュートリアルを発見しました。私はコードを入力し、構文をswift3に変換しましたが、起動時にアプリケーションが壊れます。これは、私がログインしていることを知っていることを意味しますが、何らかの理由でセグがロードされず、アプリケーションが壊れてしまいます。私が得るエラーは、スレッド1:sigabrtです。ここで

は、最初の初期ビューコントローラでのストーリーボードの外観で、関連する項目は、左側にあり、ユーザーがログインしている場合、私は右 1

+0

あなたはストーリーボードIDを定義しましたか? –

+0

実際のデバイスを使用していますか? –

答えて

0
上のViewControllerから起動するアプリをする方法であります

あなたのコードは大丈夫です。ストーリーボードのデザイン画面のIDセクションで、ViewControllerのストーリーボードIDを確認することを検討する必要があります。ストーリーボードIDには "ViewController"を指定する必要があります。ログイン画面のストーリーボードIDはあなたのコードに従って "facebookLogin"にする必要があります。

+0

ええ私はすでにそれをしています – pbokey

+0

正常にログインした後、あなたのボタンのプロセスの背後にあるコードを試してみませんか? 'let vc = self.storyboard?.instantiateViewControllerWithIdentifier(" ViewController ")as! UIViewController; self.presentViewController(vc、animated:true、completion:nil); ' –

0

現在のアクセストークンはnilです。最新のFBSDKはシミュレータのアクセストークンを保存していないため、実際のデバイスをチェックインしようとします。それが印刷され、コンソールに「なぜなら、シミュレータのバグのNSUserDefaultsからロードアクセストークンにフォールバック」

----編集----ここ

は、現在のアクセストークンがnilであれば、それは行くよりも、ログイン画面へ。あなたの要件に応じて次の条件を変更します。

if(FBSDKAccessToken.current() != nil) { 
     let vc = mainStoryBoard.instantiateViewController(withIdentifier: "ViewController") as! ViewController 
     initialViewController = vc 
} 
else { 
    initialViewController = mainStoryBoard.instantiateViewController(withIdentifier: "facebookLogin") 
} 

あなたの要件としてinitialViewControllerを変更してください。 iOSシミュレータを使用した場合

----更新----あなたはこの警告を無視することができます

は、それがハードコーディングされていますFacebookSDKに。 SDKにはバグがありますが、シミュレータがアクセストークンをキャッシュできません。 94とFBSDKKeychainStore.m:135直前:

あなたはFBSDKKeychainStore.mに次の行 を追加することによってこの問題を解決することができ

let key = String(format: "%@_fix", key) 
UserDefaults().set(key, forKey: value) 
+0

これは、シミュレータの値を格納していない場合、my if ... elseステートメントの性質によって、 ? – pbokey

0

スウィフト3コード

//チェック最終AccesToken

if let accessToken = AccessToken.current { 
     print("Last AccesToken -\(accessToken)") 

     // Redirect to next screen 
     self.performSegue(withIdentifier:"NextScreen", sender: self) 
    } 
    else { 

     let loginManager = LoginManager() 
     loginManager.loginBehavior = LoginBehavior.web 
     loginManager.logIn([ .publicProfile , .email, .userFriends], viewController: self) { loginResult in 
      switch loginResult { 

      case .failed(let error): 
       print(error) 
       break 
      case .cancelled: 
       print("User cancelled login.") 
       break 
      case .success(let grantedPermissions, let declinedPermissions, let accessToken): 
       print("Logged in! \(grantedPermissions) \(accessToken) \(declinedPermissions)") 

       // Save Current UserInfo 
       let params = ["fields":"id,name,email,picture"] 
       let graphRequest = GraphRequest(graphPath: "me", parameters: params) 
       graphRequest.start { (urlResponse, requestResult) in 
        switch requestResult { 
        case .failed(let error): 
         print(error) 
        case .success(let graphResponse): 
         if let responseDictionary = graphResponse.dictionaryValue { 

          print("\(String(describing: graphResponse.dictionaryValue))") 

          UserDefaults.standard.set(responseDictionary, forKey: "userInfo") 
         } 
        } 
       } 

       self.performSegue(withIdentifier: "NextScreen", sender: self) 
       break 
      } 
     } 
    } 
関連する問題