2016-04-30 103 views
1

我有一個主頁,用戶必須使用Facebook登錄登錄。但是當我點擊Facebook按鈕時 - 它會將我引導至Safari頁面,並自動退出並返回主屏幕。無法使用Facebook SDK登錄

我嘗試了所有的教程和更改代碼,但沒有爲我工作。請幫助我 - 爲什麼會發生這種情況?

import UIKit 
import FBSDKCoreKit 
import FBSDKLoginKit 

class LoginViewController: UIViewController, UIAlertViewDelegate, GIDSignInDelegate, GIDSignInUIDelegate 
{ 

    @IBOutlet weak var UsernameEmailTextField: UITextField? // init username/email text field 
    @IBOutlet weak var PasswordTextField: UITextField? // init password text field 
    @IBOutlet var FbLoginButton: UIButton! 

    override func viewDidLoad() { 
     super.viewDidLoad() 
     self.navigationController?.navigationBar.barTintColor = UIColor.redColor() 
     self.navigationController?.navigationBar.tintColor = UIColor.whiteColor() 

     if (FBSDKAccessToken.currentAccessToken() != nil) { 
      // User is already logged in, do work such as go to next view controller. 
      print("User Already Logged In") 
     } else { 
      print("User Not Logged In") 
     } 

     let dismiss: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(LoginViewController.DismissKeyboard)) 
     view.addGestureRecognizer(dismiss) 
    } 

    //keyboard dismiss function for input's 
    func DismissKeyboard() { 
     view.endEditing(true) 
    } 

    //facebook sign in 
    @IBAction func FbLoginButtonTapped(sender: AnyObject) { 
     let facebookLogin = FBSDKLoginManager() 
     facebookLogin.logInWithReadPermissions(["email","public_profile","user_location"], fromViewController:self, handler:{(facebookResult, facebookError) -> Void in 

       if facebookError != nil { 
        print("Facebook login failed. Error \(facebookError)") 
       } else if facebookResult.isCancelled { 
        print("Facebook login was cancelled.") 
       } else { 
        if((FBSDKAccessToken.currentAccessToken()) != nil) { 
         FBSDKGraphRequest(graphPath: "me", 
          parameters: ["fields": "id, name, first_name, last_name, picture.type(large), email, user_location"]).startWithCompletionHandler({ 
           (connection, result, error) -> Void in 

           if (error != nil) { 
            print(error) 
           } else { 
            let Email = result.valueForKey("email") as! String 
            let IdasPassword = result.valueForKey("id") as! String 
            self.MakeLogin(Email, SocialPassword: IdasPassword) 
           } 
          }) 
        } 

       } 
     }) 

    } 

    func MakeLogin(SocialEmail: String, SocialPassword: String) { 
     //Adding Headers 
     let headers = ["content-type": "application/x-www-form-urlencoded"] 
     //Concatenating the email/username field with postdata 
     let ConcatEmail = "email="+SocialEmail 
     //Concatenating the password field with postdata 
     let ConcatPassword = "&password="+SocialPassword 
     //assigning concatenated values in postData 
     let postData = NSMutableData(data: ConcatEmail.dataUsingEncoding(NSUTF8StringEncoding)!) 
     postData.appendData(ConcatPassword.dataUsingEncoding(NSUTF8StringEncoding)!) 
     //assigning request values 
     let request = NSMutableURLRequest(URL: NSURL(string: "http login url」)!) 
      //declaring POST Method 
      request.HTTPMethod = "POST" 
      //declaring header fields 
      request.allHTTPHeaderFields = headers 
      //Adding postData as HTTPBody 
      request.HTTPBody = postData 
     //declaring the session for url 
     let session = NSURLSession.sharedSession() 
     //assigning task to get response data 
     let task = session.dataTaskWithRequest(request, completionHandler: { (ResposeData, response, error) -> Void in 
      if(ResposeData != nil) { 
       //declaring completion handler to check whether login. 
       do { 
        if let jsonData = try NSJSONSerialization.JSONObjectWithData(ResposeData!, options: []) as? NSDictionary { 
         //assigning success jsonData 
         if let success = jsonData["success"] as? Int { 
          //If login success 
          if(success == 1) { 
           //assign access_token value from jsonData 
           let access_token = jsonData["token"] 
           // loading menu 
           dispatch_async(dispatch_get_main_queue()) { 
            let appdelegate:AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate 
            _ = appdelegate.window!.rootViewController 
            let mainStoryBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil) 
            let mainViewController = mainStoryBoard.instantiateViewControllerWithIdentifier("HomeViewController") as! HomeViewController 
            let leftViewController = mainStoryBoard.instantiateViewControllerWithIdentifier("MenuViewController") as! MenuViewController 
            let leftSideNav = UINavigationController(rootViewController: leftViewController) 
            let centerNav = UINavigationController(rootViewController: mainViewController) 
            let centerContainer:MMDrawerController = MMDrawerController(centerViewController: centerNav, leftDrawerViewController: leftSideNav) 
            centerContainer.openDrawerGestureModeMask = MMOpenDrawerGestureMode.PanningCenterView; 
            centerContainer.closeDrawerGestureModeMask = MMCloseDrawerGestureMode.PanningCenterView; 
            NSUserDefaults.standardUserDefaults().setBool(true, forKey: "ISSOCIALLOGGEDIN") 
            NSUserDefaults.standardUserDefaults().setValue(access_token, forKey: "access_token") 
            NSUserDefaults.standardUserDefaults().synchronize() 
            appdelegate.centerContainer = centerContainer 
            appdelegate.window!.rootViewController = appdelegate.centerContainer 
            appdelegate.window!.makeKeyAndVisible() 
           } 

           //dismissing the current view 
           self.dismissViewControllerAnimated(true, completion: nil) 
          } else { 
           let ServerMessage = jsonData["message"] as? String 
           print(ServerMessage) 
           dispatch_async(dispatch_get_main_queue(), { 
            let alert = UIAlertController(title: "Error", message: ServerMessage, preferredStyle: UIAlertControllerStyle.Alert) 
            // add an action (button) 
            alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil)) 
            // show the alert 
            self.presentViewController(alert, animated: true, completion: nil) 
           }) 
          } 
         } 
        } else { 
         let jsonStr = NSString(data: ResposeData!, encoding: NSUTF8StringEncoding) 
         // No error thrown, but not NSDictionary 
         print("Error could not parse JSON: \(jsonStr)") 
        } 

       } catch let parseError { 
        print(parseError) 
        // Log the error thrown by `JSONObjectWithData` 
        let jsonStr = NSString(data: ResposeData!, encoding: NSUTF8StringEncoding) 
        print("Error could not parse JSON: '\(jsonStr)'") 
        dispatch_async(dispatch_get_main_queue(), { 
         let alert = UIAlertController(title: "Error", message: "No Data Received, Please contact Admin/Dev", preferredStyle: UIAlertControllerStyle.Alert) 
         // add an action (button) 
         alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil)) 
         // show the alert 
         self.presentViewController(alert, animated: true, completion: nil) 
        }) 
       } 
      } else { 
       print("Error: No Response Data") 
       dispatch_async(dispatch_get_main_queue(), { 
        let alert = UIAlertController(title: "Invalid Username or Password", message: "No Response from server, You might be facing internet failure or try with different values", preferredStyle: UIAlertControllerStyle.Alert) 
        // add an action (button) 
        alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil)) 
        // show the alert 
        self.presentViewController(alert, animated: true, completion: nil) 
       }) 
      } 
     }) 
     task.resume() 
    } 
} 
+0

任何日誌???????? –

+0

沒有日誌,只是來登錄屏幕或一段時間它只是在Safari瀏覽器頁面 – user5513630

+0

意味着它崩潰或不... –

回答

0

首先,我假設你的項目中有最新版本的Facebook SDK。首先,通過所有的關於SDK安裝Facebook的開發者網站上提到的步驟,

This將幫助你在情況下,你不能轉換Objective-C代碼爲斯威夫特。

展望未來,要實現在yourViewController的功能,如func loginButton(loginButton: FBSDKLoginButton!, didCompleteWithResult result: FBSDKLoginManagerLoginResult!, error: NSError!)的去了解,當用戶按下登錄鍵,就這樣發生了什麼事:只要你的電子郵件

func loginButton(loginButton: FBSDKLoginButton!, didCompleteWithResult result: FBSDKLoginManagerLoginResult!, error: NSError!) { 
     if (error != nil) { 
      print(error.localizedDescription) 
     } else if result.isCancelled { 
      print("User Cancelled The Login") 
     } else { 
      if result.grantedPermissions.contains("email") { 
       print("Got email access") 
      } 
     } 
    } 

訪問,您可以調用另一個函數來獲取您要求的用戶詳細信息;這就是:

func graphRequestToReturnUserData(graphParameters: Dictionary<String, String>) { 
     let graphRequest: FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me", parameters: graphParameters) 
     graphRequest.startWithCompletionHandler({ 
      (connection, result, error) -> Void in 
      if ((error) != nil) { 
       print("Error: \(error.localizedDescription)")  //Error Handling 
      } else { 
       self.facebookD = result as! NSDictionary 
      } 
     }) 
    } 

創建您自己的按鈕,然後去詳細信息是不是一個好辦法,當一切都已經在SDK中。 除此之外,您還需要提及您所需的權限。

+0

當我使用seperare項目,我的FB登錄工作正常。但是當我在這個項目中使用。它不工作.Ok通過您的建議 - 如果我使用委託協議,如果在我的代碼中使用委託方法意味着如何做到這一點。我的意思是如何重新編碼我的代碼!!!! ?? – user5513630

+0

只需實施代表。 – Fennec

+0

用我現在的代碼,如果我實現委託,它會工作嗎? – user5513630