2015-04-20 226 views
8

在Xcode中,如果我創建了一個UIView,然後將自定義類添加爲FBSDKLoginButton,當我單擊它時會引導我通過Facebook登錄,然後將我返回到與FBSDKLoginButton相同的頁面,但不是說登錄按鈕它說現在註銷。我會如何去做,當登錄按鈕被點擊它導致一個新的觀點?Swift的Facebook登錄按鈕


我通過cocoapods下載了Facebook SDK並且第一次使用它,所以我對此感到困惑。謝謝您的幫助!

+0

您應該檢查成功回調(即登錄=成功)在視圖中。如果你已經登錄,你可以「重定向」到另一個視圖。 –

+0

這可能是一個愚蠢的問題,但我該怎麼做,因爲在視圖控制器中沒有實際的代碼? – Soporificdreamer

回答

20

一種選擇是將您的視圖控制器設置爲FBSDKLoginButton的代理並實現loginButton:didCompleteWithResult:error:方法,該方法在按鈕用於登錄時調用。

斯威夫特

class ViewController: UIViewController, FBSDKLoginButtonDelegate { 

    @IBOutlet weak var loginButton: FBSDKLoginButton!   

    override func viewDidLoad() { 
     super.viewDidLoad() 

     self.loginButton.delegate = self 
    } 
} 

對象 -

// ViewController.h 
@interface ViewController : UIViewController <FBSDKLoginButtonDelegate> 

@property (weak, nonatomic) IBOutlet FBSDKLoginButton *loginButton; 

@end 

// ViewController.m 
@implementation ViewController 

- (void)viewDidLoad { 
    [super viewDidLoad]; 

    self.loginButton.delegate = self; 
} 

然後,在loginButton:didCompleteWithResult:error:方法,你可以檢查resulterror,如果一切都很好,導航到另一個視圖。

斯威夫特

func loginButton(loginButton: FBSDKLoginButton!, didCompleteWithResult result: FBSDKLoginManagerLoginResult!, error: NSError!) { 
     if ((error) != nil) { 
      // Process error 
     } 
     else if result.isCancelled { 
      // Handle cancellations 
     } 
     else { 
      // Navigate to other view 
     } 
    } 

對象 -

// ViewController.m 
@implementation ViewController 

- (void)loginButton:(FBSDKLoginButton *)loginButton 
    didCompleteWithResult:(FBSDKLoginManagerLoginResult *)result 
        error:(NSError *)error { 
    if (error) { 
     // Process error 
    } 
    else if (result.isCancelled) { 
     // Handle cancellations 
    } 
    else { 
     // Navigate to other view 
    } 
} 

你可以找到更多有關如何使用FB在their docs登錄。

+0

工作原理自動登錄? – jose920405

0

你可以這樣做就像從appcoda本教程中(見下面的代碼)

- (void)viewDidLoad { 
    [super viewDidLoad]; 
    self.title = @"Facebook Profile"; 

    // Check if user is cached and linked to Facebook, if so, bypass login  
    if ([PFUser currentUser] && [PFFacebookUtils isLinkedWithUser:[PFUser currentUser]]) { 
     [self.navigationController pushViewController: [[UserDetailsViewController alloc] initWithStyle:UITableViewStyleGrouped] animated:NO]; 
    } 

} 


#pragma mark - Login methods 

/* Login to facebook method */ 

- (IBAction)loginButtonTouchHandler:(id)sender { 
    // Set permissions required from the facebook user account 
    NSArray *permissionsArray = @[ @"user_about_me", @"user_relationships", @"user_birthday", @"user_location"]; 

// Login PFUser using facebook 
[PFFacebookUtils logInWithPermissions:permissionsArray block:^(PFUser *user, NSError *error) { 
    [_activityIndicator stopAnimating]; // Hide loading indicator 

    if (!user) { 
     if (!error) { 
      NSLog(@"Uh oh. The user cancelled the Facebook login."); 
      UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Log In Error" message:@"Uh oh. The user cancelled the Facebook login." delegate:nil cancelButtonTitle:nil otherButtonTitles:@"Dismiss", nil]; 
      [alert show]; 
     } else { 
      NSLog(@"Uh oh. An error occurred: %@", error); 
      UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Log In Error" message:[error description] delegate:nil cancelButtonTitle:nil otherButtonTitles:@"Dismiss", nil]; 
      [alert show]; 
     } 
    } else if (user.isNew) { 
     NSLog(@"User with facebook signed up and logged in!"); 
     [self.navigationController pushViewController:[[UserDetailsViewController alloc] initWithStyle:UITableViewStyleGrouped] animated:YES]; 
    } else { 
     NSLog(@"User with facebook logged in!"); 
     [self.navigationController pushViewController:[[UserDetailsViewController alloc] initWithStyle:UITableViewStyleGrouped] animated:YES]; 
     } 
    }]; 

    [_activityIndicator startAnimating]; // Show loading indicator until login is finished 
} 

下面是這個demo app

+1

這是在審查隊列中找到我的,因爲它被標記爲只有鏈接的答案,在這裏通常不被看好。我可以看到你已經回覆了關於僅鏈接答案的評論。我編輯整理了一些格式/拼寫錯誤。 –

3

在斯威夫特這將是這樣的:對雨燕的LoginButton委託

@IBAction func unwindToViewOtherController(segue:UIStoryboardSegue) { 
    } 
+0

感謝bud ..一小段這證明得心應手! –

+0

'執行SegueWithIdentifier(「unwindToViewOtherController」,發件人:自我)'內部'if(FBSDKAccessToken.currentAccessToken()!= nil)'不加載下一個viewcontroller。你會幫助我嗎? – rAzOr

+0

在故事板中,選擇展開順序,然後選擇屬性檢查器。在那裏你應該有'unwindToViewOtherController'作爲**標識符**和'unwindToViewOtherController:'作爲** Action **。 –

2

在當前FacebookLogin版本(0.2.0):

class MyViewController: UIViewController, FBSDKLoginButtonDelegate { 
    @IBOutlet weak var loginView : FBSDKLoginButton! 
    @IBOutlet weak var profilePictureView : FBSDKProfilePictureView! 

    override func viewDidLoad() { 
     super.viewDidLoad() 

     self.loginView.delegate = self 

     if (FBSDKAccessToken.currentAccessToken() != nil) 
     { 
      performSegueWithIdentifier("unwindToViewOtherController", sender: self) 
     } 
     else 
     { 
      loginView.readPermissions = ["public_profile", "email", "user_friends"] 
     } 

    } 

    func loginButton(loginButton: FBSDKLoginButton!, didCompleteWithResult result: FBSDKLoginManagerLoginResult!, error: NSError!) { 
     println("User Logged In") 

     if ((error) != nil) 
     { 
      // Process error 
     } 
     else if result.isCancelled { 
      // Handle cancellations 
     } 
     else { 
      // If you ask for multiple permissions at once, you 
      // should check if specific permissions missing 
      if result.grantedPermissions.contains("email") 
      { 
       // Do work 
      } 
     } 
    } 

    func loginButtonDidLogOut(loginButton: FBSDKLoginButton!) { 
     println("User Logged Out") 
    } 
} 

然後在你的TargetViewController添加一個展開函數屬性被定義爲強屬性:

public class LoginButton: UIView { 
... 
    /// Delegate of the login button that can handle the result, logout events. 
public var delegate: LoginButtonDelegate? 
... } 

如果添加登錄以下按鈕Facebook的指示,你設置你的UIViewController子類的按鈕代表...

...參考週期將被創建。該視圖將包含對該按鈕的強烈引用,該按鈕將包含對控制器的強引用,並且控制器將對其視圖有強烈的引用,請參閱此post

我的解決辦法是使用一個弱成員變量必須登錄按鈕的引用,當視圖中消失,按鈕委託設置爲nil,就像這樣:

import UIKit 
import FacebookCore 
import FacebookLogin 
import RxSwift 

class LoginViewController: UIViewController, LoginButtonDelegate { 

    private weak var facebookLoginButton: LoginButton? = nil 

    override func viewDidLoad() { 

     super.viewDidLoad() 

     // Add the Facebook login button 
     let loginButton = LoginButton(readPermissions: [ .publicProfile, .email, .userFriends ]) 
     loginButton.center = view.center 
     // WARNING!: Facebook login button delegate property is defined currently as STRONG. 
     // Therefore, it must be set to nil before leaving the view to avoid reference cycles 
     loginButton.delegate = self 
     view.addSubview(loginButton) 
     // Store the login button as a weak reference, since it is holded by the main view with a 
     // strong reference 
     facebookLoginButton = loginButton 
    } 

    override func willMove(toParentViewController parent: UIViewController?) { 
     super.willMove(toParentViewController:parent) 
     if parent == nil { 
      // The back button was pressed, interactive gesture used, or programatically pop view 
      // was executed 
      // Do not forget to set delegate in Facebook button to nil to break reference cycle. 
      facebookLoginButton?.delegate = nil 
     } 
    } 

    // MARK: - Facebook login 

    /** 
    Called when the button was used to login and the process finished. 

    - parameter loginButton: Button that was used to login. 
    - parameter result:  The result of the login. 
    */ 
    func loginButtonDidCompleteLogin(_ loginButton: LoginButton, result: LoginResult) { 

     switch result { 
      case .failed(let error): 
       // Action on failed 
      case .cancelled: 
       // Action on cancelled 
      case .success(let grantedPermissions, let declinedPermissions, let accessToken): 
       // Action on success 
     } 
    } 

    /** 
    Called when the button was used to logout. 

    - parameter loginButton: Button that was used to logout. 
    */ 
    func loginButtonDidLogOut(_ loginButton: LoginButton) { 

     // Action on logout 
    } 
} 

不要使用功能viewWillDissapear()設置爲nil委託,因爲Facebook登錄頁面將顯示在您的應用程序頂部,觸發此功能,並且您將不會得到登錄結果,因爲您不再是委託人。請注意,this solution在導航控制器中的視圖正常工作。應該爲模態窗口找到另一個解決方案。

我希望它能幫助, 哈維

+2

如果你放棄說「這是一條評論」的話......這實際上看起來像是對我的回答;-) – GhostCat