在ViewController之间传输数据而不使用Segues - Swift

时间:2017-11-22 13:07:55

标签: ios swift

我有一个注册viewController(VC)。一旦用户提交了他的注册详细信息,我的远程服务器就会响应“registration_success”。收到此消息后,我能够提供一个新VC,请求用户检查其电子邮件以验证其电子邮件地址。我能够呈现新的视图控制器,但无法将用户的电子邮件地址传输到新的VC。我的代码如下:

     guard
          let registeredEmail = myArray["email"] as? String else{
          print("cannot find email address")
          return
          }

          let verifyEmailVC = self.storyboard?.instantiateViewController(withIdentifier: "emailConfirmVC") as! VerifyEmailViewController
          print("registeredEmail: \(registeredEmail)")
          verifyEmailVC.emailToVerify.text! = registeredEmail
          self.present(verifyEmailVC, animated: true, completion: nil)

类VerifyEmailViewController:

    class VerifyEmailViewController: UIViewController {

    @IBOutlet var emailToVerify: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()

    }

}

控制台:

 jsonObject: {
email = "tran123@gmail.com";
firstname = Wang;
lastname = tran;
message = "registration_success";
status = 200;
userId = 53;
}
message: registration_success
registeredEmail: tran123@gmail.com

我收到以下错误:

  

线程1:致命错误:在展开时出乎意料地发现nil   可选值

排成一行:verifyEmailVC.emailToVerify.text! = registeredEmail

3 个答案:

答案 0 :(得分:1)

我修改了您的代码,但很少修正,请尝试以下代码

let verifyEmailVC = self.storyboard?.instantiateViewController(withIdentifier: "emailConfirmVC") as! VerifyEmailViewController
      print("registeredEmail: \(registeredEmail)")
      verifyEmailVC.emailToVerifyStr = registeredEmail
      self.present(verifyEmailVC, animated: true, completion: nil)

VerifyEmailViewController

    class VerifyEmailViewController: UIViewController {

    var emailToVerifyStr = ""
    @IBOutlet var emailToVerify: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()

    }

    override func viewWillAppear(_ animated:Bool){
       super.viewWillAppear(true)
       self.emailToVerify.text = emailToVerifyStr
    }
  }

希望能帮助你:)

答案 1 :(得分:0)

VerifyViewController中的标签为零,您正在尝试将值设置为该标签。尝试将字符串传递给控制器​​,如下所示

let verifyEmailVC = self.storyboard?.instantiateViewController(withIdentifier: "emailConfirmVC") as! VerifyEmailViewController
print("registeredEmail: \(registeredEmail)")
verifyEmailVC.email = registeredEmail
self.present(verifyEmailVC, animated: true, completion: nil)


class VerifyEmailViewController: UIViewController {

@IBOutlet var emailToVerify: UILabel!
var email: String?

override func viewDidLoad() {
    super.viewDidLoad()
    emailToVerify.text = email
}

答案 2 :(得分:0)

首先,我想推荐使用像ViewController这样的高级对象使用的JSON对象。

您应该考虑使用“ Store ”对象接收JSON,创建用户对象

然后,您可以直接创建一个init功能传递您的用户对象

像这样:

- (instancetype)initWithUser(User *)user {
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];

   self = [storyboard instantiateViewControllerWithIdentifier:@"emailConfirmVC"];

   if(self) {
      //default initialization
   }

   return  self;
 }