Search code examples
swiftios-simulator

I have a black screen on my App when I open the Simulator


I'm making an App by coding (so there isn't any ViewController in the StoryBoard), but when I try to build my app, there is a white screen and immediately a black screen.

There are no Thread errors.

Is someone can help me ? Thanks

This is the code :

import UIKit import FirebaseAuth

class LoginViewController: UIViewController {

private let scrollView: UIScrollView = {
    let scrollView = UIScrollView()
    
    scrollView.clipsToBounds = true
    
    return scrollView
}()

private let logoView: UIImageView = {
    let logoView = UIImageView()
    logoView.image = UIImage(named: "logo")
    logoView.contentMode = .scaleAspectFit
    return logoView
}()

private let emailField: UITextField = {
    let field = UITextField()
    
    field.autocapitalizationType = .none
    field.autocorrectionType = .no
    field.returnKeyType = .continue
    field.layer.cornerRadius = 12
    field.layer.borderWidth = 1
    field.layer.borderColor = UIColor.lightGray.cgColor
    field.placeholder = "Email Address"
    field.leftView = UIView(frame: CGRect(x: 0,
                                          y: 0,
                                          width: 10,
                                          height: 0))
    field.leftViewMode = .always
    field.backgroundColor = .white
    
    return field
} ()

private let passwordField: UITextField = {
    let field = UITextField()
    
    field.autocapitalizationType = .none
    field.autocorrectionType = .no
    field.returnKeyType = .send
    field.layer.cornerRadius = 12
    field.layer.borderWidth = 1
    field.layer.borderColor = UIColor.lightGray.cgColor
    field.placeholder = "Password"
    field.leftView = UIView(frame: CGRect(x: 0,
                                          y: 0,
                                          width: 10,
                                          height: 0))
    field.leftViewMode = .always
    field.backgroundColor = .white
    field.isSecureTextEntry = true
    
    return field
} ()


private let loginButton: UIButton = {
   let button = UIButton()
    button.setTitle("Log In", for: .normal)
    button.backgroundColor = .link
    button.setTitleColor(.white, for: .normal)
    button.layer.cornerRadius = 12
    button.layer.masksToBounds = true
    button.titleLabel?.font = .systemFont(ofSize: 20, weight: .bold)
    return button
}()






override func viewDidLoad() {
    super.viewDidLoad()
    title = "Log In"
    view.backgroundColor = .white
    
    navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Register",
                                                        style: .done,
                                                        target: self,
                                                        action: #selector(didTapRegister))
    
    loginButton.addTarget(self,
                          action: #selector(loginButtonTapped),
                          for: .touchUpInside)
    
    
    emailField.delegate = self
    passwordField.delegate = self
    
    // Add subviews
    view.addSubview(scrollView)
    scrollView.addSubview(logoView)
    scrollView.addSubview(emailField)
    scrollView.addSubview(passwordField)
    scrollView.addSubview(loginButton)

   
}

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    scrollView.frame = view.bounds
    
    let size = view.width/3
    logoView.frame = CGRect(x: (scrollView.width-size)/2,
                            y: 20,
                            width: size,
                            height: size)
    emailField.frame = CGRect(x: 30,
                              y: logoView.bottom+25 ,
                              width: scrollView.width-60,
                              height: 52)
    passwordField.frame = CGRect(x: 30,
                                 y: emailField.bottom+15 ,
                                 width: scrollView.width-60,
                                 height: 52)
    loginButton.frame = CGRect(x: 30,
                                 y: passwordField.bottom+30 ,
                                 width: scrollView.width-60,
                                 height: 52)
}


@objc private func loginButtonTapped() {
    
    emailField.resignFirstResponder()
    passwordField.resignFirstResponder()
    
    guard let email = emailField.text, let password = passwordField.text, !email.isEmpty, !password.isEmpty, password.count >= 6 else {
            alertUserLoginError()
            return
    }
    
    // Firebase Log In
    FirebaseAuth.Auth.auth().signIn(withEmail: email, password: password, completion: { [weak self] authResult, error in
        guard let strongSelf = self else {
            return
        }
        guard let result = authResult, error == nil else {
            print("Failed to log in with email: \(email)")
            
            return
        }
        let user = result.user
        print("Logged In user \(user)")
        strongSelf.navigationController?.dismiss(animated: true, completion: nil)
    })
    
}

func alertUserLoginError() {
    let alert = UIAlertController(title: "Woops",
                                  message: "Please enter all information to log in.",
                                  preferredStyle: .alert)
    
    alert.addAction(UIAlertAction(title: "Dismiss",
                                  style: .cancel,
                                  handler: nil))
    
    present(alert, animated: true)
}

func emailOrPasswordIncorrect() {
    let alert = UIAlertController(title: "Woops",
                                  message: "Incorrect email or password. Please retry.",
                                  preferredStyle: .alert)
    
    alert.addAction(UIAlertAction(title: "Dismiss",
                                  style: .cancel,
                                  handler: nil))
    
    present(alert, animated: true)
}

@objc private func didTapRegister() {
    let vc = RegisterViewController()
    vc.title = "Create Account"
    navigationController?.pushViewController(vc, animated: true)
}

}

extension LoginViewController: UITextFieldDelegate {

func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    
    if textField == emailField {
        passwordField.becomeFirstResponder()
    } else if textField == passwordField {
        loginButtonTapped()
    }
    
    return true
}

}


Solution

  • if Main Interface in General tab is empty You need to create yuor own Window in appDelegate's didFinishLaunchingWithOptions func, add root controller to it and make this window keyAndVisible to see your controller

    AppDelegate.swift

     func application(_ application: UIApplication,
                         didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
            window = UIWindow(frame: UIScreen.main.bounds)
            window.rootViewController = LoginViewController()
            window.makeKeyAndVisible()
            return true
        }