2017-04-20 149 views
0

因此,我試圖讓用戶通過Facebook註冊,所以他們會點擊Facebook按鈕,授權我們的應用程序,然後將它們延伸到註冊屏幕與字段「電子郵件」和「全名」填寫了我們從Facebook圖形請求收到的值。但是,我無法讓它工作。從一個視圖控制器的文本值到另一個

這是第一個視圖控制器,其中Facebook的按鈕

import UIKit 
import FBSDKLoginKit 

    //[Facebook, 2017] 
class RegisterVC: UIViewController, FBSDKLoginButtonDelegate { 
var fbLoginSuccess = false 

var fbName:String! 
var fbEmail:String! 

//[Facebook, 2017] 
override func viewDidLoad() { 
    super.viewDidLoad() 

    let loginButton = FBSDKLoginButton() 
    view.addSubview(loginButton) 
    loginButton.frame = CGRect(x: 82, y: 325, width: view.frame.width - 210, height: 59) 

    loginButton.delegate = self 
} 

//[Facebook, 2017] 
func loginButtonDidLogOut(_ loginButton: FBSDKLoginButton!) { 
    print("Did log out of facebook") 
} 

//[Facebook, 2017] 
func loginButton(_ loginButton: FBSDKLoginButton!, didCompleteWith result: FBSDKLoginManagerLoginResult!, error: Error!) { 
    if error != nil { 
     print(error) 
     return 
    } 
    print("Successfully logged in") 

    FBSDKGraphRequest(graphPath: "/me", parameters: ["fields": "id, name, email"]).start {(connection, result, err) in 
     if err != nil { 
      print("Failed to start graph request", err) 
      return 
     } else { 
      /*guard let data = result as? [String:Any] else {return} 

      let fbEmail = data["email"] as! String 
      let fbName = data["name"] as! String 

      print(fbEmail) 
      print(fbName) 

      func prepare(for segue: UIStoryboardSegue, sender: Any?) { 
       let vc = segue.destination as? CreateAccountVC 
       vc!.emailTxtValue = self.fbName 
       vc!.fullnameTxtValue = self.fbEmail 
       */ 
      } 

     guard let data = result as? [String:Any] else {return} 

     let fbEmail = data["email"] as! String 
     let fbName = data["name"] as! String 

     print(fbEmail) 
     print(fbName) 

     func prepare(for segue: UIStoryboardSegue, sender: Any?) { 
      if let vc = segue.destination as? CreateAccountVC { 
      vc.emailTxtValue = self.fbName 
      vc.fullnameTxtValue = self.fbEmail 
      } 
     } 


     print(result) 
    } 

    performSegue(withIdentifier: "regSegue", sender: RegisterVC.self) 

} 

//override func prepare(for segue: UIStoryboardSegue, sender: Any?) { 
    //get destination view an set the fullname 



    //performSegue(withIdentifier: "regSegue", sender: RegisterVC.self) 

//} 



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





} 

這裏是應該顯示的信息的文本字段下一個視圖控制器從Facebook

import UIKit 

class CreateAccountVC: UIViewController { 

var emailTxtValue: String? 
var fullnameTxtValue: String? 

@IBOutlet weak var usernameTxt: UITextField! 
@IBOutlet weak var emailTxt: UITextField! 
@IBOutlet weak var passwordTxt: UITextField! 
@IBOutlet weak var fullnameTxt: UITextField! 

override func viewDidLoad() { 
    //fullname.text = fbName 
    //email.text = fbEmail 
    super.viewDidLoad() 
    emailTxt.text = emailTxtValue 
    fullnameTxt.text = fullnameTxtValue 
    print(emailTxtValue) 
    print("here") 
    print(fullnameTxtValue) 


} 

func isValidEmail(emailTxt:String) -> Bool { 
    // print("validate calendar: \(testStr)") 
    let emailRegEx = "[A-Z0-9a-z._%+-][email protected][A-Za-z0-9.-]+\\.[A-Za-z]{2,}" 
    let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx) 
    return emailTest.evaluate(with: emailTxt) 
} 

/*func isValidPassword(passwordTxt:String) -> Bool { 
    let passwordRegEx = "{8,}" 
    let passwordTest = NSPredicate(format:"SELF MATCHES %@", passwordRegEx) 
    return passwordTest.evaluate(with: passwordTxt) 
} */ 

func isValidUsername(usernameTxt:String) -> Bool { 
    let usernameRegEx = "[a-z0-9_-]{5,16}" 
    let usernameTest = NSPredicate(format:"SELF MATCHES %@", usernameRegEx) 
    return usernameTest.evaluate(with: usernameTxt) 
} 

//[Idigov, 2017] 
@IBAction func create(_ sender: AnyObject) { 
    if usernameTxt.text!.isEmpty || passwordTxt.text!.isEmpty || emailTxt.text!.isEmpty || fullnameTxt.text!.isEmpty { 

     usernameTxt.attributedPlaceholder = NSAttributedString(string: "username", attributes: [NSForegroundColorAttributeName: UIColor.red]) 
     emailTxt.attributedPlaceholder = NSAttributedString(string: "email", attributes:[NSForegroundColorAttributeName: UIColor.red]) 
     passwordTxt.attributedPlaceholder = NSAttributedString(string: "password", attributes: [NSForegroundColorAttributeName: UIColor.red]) 
     fullnameTxt.attributedPlaceholder = NSAttributedString(string: "fullname", attributes: [NSForegroundColorAttributeName: UIColor.red]) 

     let alertController = UIAlertController(title: "Error", message: "At least one of the values entered was not valid", preferredStyle: UIAlertControllerStyle.alert) 
     alertController.addAction(UIAlertAction(title: "Okay", style: UIAlertActionStyle.default, handler:nil)) 
     self.present(alertController, animated: true, completion: nil) 
     // if there is text within any of the textboxes it will attempt to register 

    } else if 
     isValidEmail(emailTxt: emailTxt.text!) == false { 
     let alertController = UIAlertController(title: "Error", message: "The email entered is not valid", preferredStyle: UIAlertControllerStyle.alert) 
     alertController.addAction(UIAlertAction(title: "Okay", style: UIAlertActionStyle.default, handler:nil)) 
     self.present(alertController, animated: true, completion: nil) 

    } /*else if isValidPassword(passwordTxt: passwordTxt.text!) == false{ 
      let alertController = UIAlertController(title: "Error", message: "The password entered must be at least 8 characters long", preferredStyle: UIAlertControllerStyle.alert) 
      alertController.addAction(UIAlertAction(title: "Okay", style: UIAlertActionStyle.default, handler:nil)) 
      self.present(alertController, animated: true, completion: nil) 

    } */else if isValidUsername(usernameTxt: usernameTxt.text!) == false { 
     let alertController = UIAlertController(title: "Error", message: "Your username must be 5 to 16 characters long and can only contain letters, numbers, underscores or hyphens", preferredStyle: UIAlertControllerStyle.alert) 
     alertController.addAction(UIAlertAction(title: "Okay", style: UIAlertActionStyle.default, handler:nil)) 
     self.present(alertController, animated: true, completion: nil) 
    } 

    //[Idigov, 2017] 
    else{ 


     let url = NSURL(string: "https://cgi.soic.indiana.edu/~team7/register.php")! 

     let request = NSMutableURLRequest(url: url as URL) 

     request.httpMethod = "POST" 

     let body = "username=\(usernameTxt.text!.lowercased())&password=\(passwordTxt.text!)&email=\(emailTxt.text!)&fullname=\(fullnameTxt.text!)" 
     request.httpBody = body.data(using: String.Encoding.utf8) 

     URLSession.shared.dataTask(with: request as URLRequest as URLRequest, completionHandler: { (data:Data?, response:URLResponse?, error:Error?) -> Void in 

      if error == nil { 
       DispatchQueue.main.async(execute: { 

        do { 
         let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary 
         guard let parseJSON = json else { 
          print("Error while parsing") 
          return 
         } 

         let id = parseJSON["id"] 

         if id != nil && response != nil { 
          print(parseJSON) 
         } 



        } catch { 
         print("Caught an error \(error)") 
        } 
       }) 

      } else { 
       print("error: \(error)") 
      } 

     }).resume() 
     let alertController = UIAlertController(title: "Registered", message: "Account Successfully Registered! Please Log In", preferredStyle: UIAlertControllerStyle.alert) 
     let okay = UIAlertAction(title: "Okay", style: .default, handler: {_ in CATransaction.setCompletionBlock({ 
      self.performSegue(withIdentifier: "accountSuccess", sender: nil)}) 
      }) 
     alertController.addAction(okay) 
     //alertController.addAction(UIAlertAction(title: "Okay", style: UIAlertActionStyle.default, handler:nil)) 
     self.present(alertController, animated: true, completion: nil) 
    } 
    //performSegue(withIdentifier: "accountSuccess", sender: CreateAccountVC.self) 
} 



} 

如果抓起任何人都可以幫助我找到一個令人驚歎的解決方案!謝謝!

+0

'prepare(對於segue:..'方法應該在'loginButton(_ loginButto ...'方法 –

回答

3

您需要將prepareForSegue方法放在類級別中,而不是在其他任何方法中,您還需要在完成塊內部調用performSegue而不是在完成塊之外。像下面那樣更改您的代碼。

//[Facebook, 2017] 
func loginButton(_ loginButton: FBSDKLoginButton!, didCompleteWith result: FBSDKLoginManagerLoginResult!, error: Error!) { 
    if error != nil { 
     print(error) 
     return 
    } 
    print("Successfully logged in") 

    FBSDKGraphRequest(graphPath: "/me", parameters: ["fields": "id, name, email"]).start {(connection, result, err) in 
     if err != nil { 
      print("Failed to start graph request", err) 
      return 
     } else { 
      guard let data = result as? [String:Any] else {return} 
      self.performSegue(withIdentifier: "regSegue", sender: data) 
     } 
    } 
} 

override func prepare(for segue: UIStoryboardSegue, sender: Any?) { 
    if let vc = segue.destination as? CreateAccountVC, 
    let dic = sender as? [String:Any] { 
     let fbEmail = dic["email"] as! String 
     let fbName = dic["name"] as! String 
     vc.emailTxtValue = fbEmail 
     vc.fullnameTxtValue = fbName 
    } 
} 
+0

以外的方法之外,加上他不改變self.fbEmail和self.fbName的值,而是聲明新的常量,然後在prepareForSegue他發送空self.fbName和self.fbEmail –

+0

@JaafarBarek不需要,因爲我傳遞數據作爲發件人,所以現在它將訪問'prepareforsegue'通過發件人字典像我在解決方案建議 –

+1

是以這種方式編輯它是(y)。 –

0

你有全局聲明2個變量

var fbName:String! 

var fbEmail:String! 

,當你在那個時候分配值,它正在創建相同的變量,

let fbEmail = data["email"] as! String 

let fbName = data["name"] as! String 

,所以你只需要從fbEmail和fbName中刪除讓你能夠獲得另一個視圖控制器的價值

相關問題