opening ViewController raise unexpectedly found nil while unwrapping an Optional value - ios

I'm trying to open a new ViewController from my code by using
let registrationView = NewOrdoViewController()
self.presentViewController(registrationView, animated: true, completion: nil)
my NewOrdoViewController is containing a ScrollView and while opening the new View, my app crash at the following line:
override func viewDidLoad() {
super.viewDidLoad()
scrollView.contentSize.height = 2000 <-- it crash here
......
with the following error:
unexpectedly found nil while unwrapping an Optional value
is there any specific command to instantiate a new ViewController containing a ScrollView ?

You're opening a generic NewOrdoViewController, not the instance that exists in your storyboard. Give your NewOrdoViewController a storyboard ID in the interface builder and replace
let registrationView = NewOrdoViewController()
with
let registrationView = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("YourStoryboardID") as! NewOrdoViewController

Related

Error passing value to view controller on dismiss | Swift 5

Error transferring value from one view controller to another on dismiss.
I have a value in ViewController2 that I would like to transfer to ViewController1 on dismiss. In view ViewController2 I do the following to dismiss:
func OtherFunction() {
passAndDismiss(scannedScript: stringCodeValue)
}
Note: stringCode value is indeed being passed as a String to scannedScript
func passAndDismiss(scannedScript: String) {
dismiss(animated: true, completion: {
let viewcontroller = ViewController1()
viewcontroller.Textfield1.text = scannedScript
})
}
The error occurs on line:
viewcontroller.Textfield1.text = scannedScript
The error I get is:
Unexpectedly found nil while implicitly unwrapping an Optional value
Two fatal issues:
ViewController1() is a new instance of the controller which is not the instance in the storyboard.
Solution: You need the real instance either with a segue or with instantiation from the storyboard.
Even if ViewController1() was the expected controller the outlets are not connected right after the initialization.
Solution: You have to declare a temporary property for the string in ViewController1 and assign the value to the label in viewDidLoad
Here you are initialising viewcontroller with wrong way. You should load from xib or storyboard.
In your way not initialise xib or storyboards’ ui element objects. Here textfield object nil and you are trying to access text property of that. That’s why app crashed. You should use following way:
let myViewController = MyViewController(nibName: "MyViewController", bundle: nil)
OR
let storyboard = UIStoryboard(name: "MyStoryboardName", bundle: nil)
let controller = storyboard.instantiateViewController(withIdentifier: "someViewController")
If you are not using xib or storyboard then please initialise textfield object in that controller’s init method

"Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value" - SWIFT [duplicate]

This question already has answers here:
Get attribute of viewcontroller created with storyboard
(1 answer)
What does "Fatal error: Unexpectedly found nil while unwrapping an Optional value" mean?
(16 answers)
Closed 4 years ago.
I am trying to display a custom popup menu using a UIViewController. I have written a function to enable the re-use of displaying the popup. However, I keep getting the error above and I do not know how to handle the "nil".
SWIFT:
func showPopUp(msg: String){
let storyboard = UIStoryboard.init(name: "Main", bundle: nil)
let popUpVC = storyboard.instantiateViewController(withIdentifier: "popupEmpty") as! PopUpViewController
popUpVC.messageLabel.text = msg // ""Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value" - SWIFT"
self.present(popUpVC, animated: true, completion: nil)
}
My msg parameter is not an optioanl type. I am somewhat confused.
messageLabelis nil until view loads ( even if connected properly )
class PopUpViewController:UIViewController {
var sendedText = ""
}
then use
popUpVC.sendedText = msg
//
then set sendedText to the lbl inside viewDidLoad

"performSegueWithIdentifier" gives fatal error

I am new in iOS-Swift. I created simple app, first time after log in "performSegueWithIdentifier" works fine but After logout I'm coming back to root view controller if I again log in, "performSegueWithIdentifier" gives me fetal error (crash). I am not setting any property from my login view. I don't understand y its working fine for the first time and gives error second time.
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
self.login()
}
func login() {
if user == nil {
self.presentViewController(logInView, animated: false, completion: nil)
} else {
self.performSegueWithIdentifier("Home", sender: self) // Here I m getting error after logout when i log in again.
}
}
in my second view, after logout i have written this:
self.navigationController?.popToRootViewControllerAnimated(false)
Error I get is the following:
fatal error: unexpectedly found nil while unwrapping an Optional value
My storyboard hierarchy is:
Navigation controller - ViewController(loginview)- TabbarController(HomeView)- Four tabs Two view controllers and two TableViewControllers.
From one of the TableViewController I am calling method
self.navigationController?.popToRootViewControllerAnimated(false)
Then its coming back to ViewController(loginview) but if i again try to login that time Tabbar view controller is not present. i m getting this by following code:
print("NextView = (storyboard.instantiateViewControllerWithIdentifier("Home"))") // Here only i m getting fetal error.
You can change the root view controller like this:
let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil) // "Main" is storyboard name
let viewController = mainStoryboard.instantiateViewControllerWithIdentifier("id") as UITabBarController
UIApplication.sharedApplication().keyWindow?.rootViewController = viewController;

Swift : fatal error: unexpectedly found nil and EXC_BAD_INSTRUCTION

I m new to Xcode and i m building a project with a login button. After clicking the login with details in the text field, it will redirect to the second view which is the scroll view controller. However, i got two parts of "Error"
Normally, it work with a normal view controller(login and move to the second view). I have just recreate a view controller to a scroll view controller and it did not work.
By the way, I got a build success but i just got error when i try to "login"
Can anyone explain why i got the thread error and the fatal error?
How can i resolve the problem?
login view Controller
#IBAction func LoginBtn(sender: AnyObject) {
LoginIn()
}
func LoginIn(){
let user = PFUser()
user.username = usernameTF.text!
user.password = passwordTF.text!
PFUser.logInWithUsernameInBackground(usernameTF.text!,
password:passwordTF.text! , block: { (User: PFUser?, Error
:NSError? ) -> Void in
if Error == nil{
dispatch_async(dispatch_get_main_queue()){
let Storyboard = UIStoryboard(name: "Main", bundle: nil)
let MainVC : UIViewController = Storyboard.instantiateViewControllerWithIdentifier("scrollV") as UIViewController
self.presentViewController(MainVC, animated: true, completion: nil)
}
}
else{
NSLog("Wrong!!!!")
}
})
}
Scroll View Controller
import UIKit
class ScrollViewController: UIViewController {
#IBOutlet weak var scrollView: UIScrollView!
override func viewDidLoad() {
super.viewDidLoad()
let V1 : ScrollViewController = ScrollViewController(nibName: "ScrollViewController", bundle: nil)
self.addChildViewController(V1)
self.scrollView!.addSubview(V1.view!)
V1.didMoveToParentViewController(self)
}
You are doing some forced unwrapping, which is not recommended (in general forced stuff in Swift is not recommended), and it will crash your application if the variable being unwrapped is nil. That's why forced unwrap is recommended only when you're 100% sure that you have a valid value in your optional.
In your case, it seems that V1.view! causes the crash, and this might be caused by the fact that V1 didn't successfully loaded from the nib.
Swift has made it very easy to work with nullable values. Just don't force unwrap and use optional binding instead.
#Cristik is correct. Instead of force unwrapping the variable, you should check to see if it is instantiated using the "if let" statement:
if let scrollView = self.scrollView {
if let subView = V1.view {
scrollView.addSubview(subView)
}
}

XCode 6: I can't select a view by its storyboard ID

This is the code :
let theBoard = self.storyboard!
let vc = theBoard.instantiateViewControllerWithIdentifier("myViewId") as! UIViewController // this line causes the error
The second line causes this error:
unexpectedly found nil while unwrapping an Optional value
* VERY IMPORTANT * : the error only fires when the build configuration is set to "debug". It works well when set to "release".
Why ?
You are casting UIViewController in the let vc = theBoard.instantiateViewControllerWithIdentifier("myViewId") as! UIViewController which is wrong.
You should try:
var storyboard = UIStoryboard(name: "Main", bundle: nil)
var vc = storyboard.instantiateViewControllerWithIdentifier("myViewId") as! ViewController
It all is a matter of the new syntax, functionality hasn't changed:
let storyboard = UIStoryboard(name: "MyStoryboardName", bundle: nil)
let vc = storyboard.instantiateViewControllerWithIdentifier("someViewController") as! UIViewController
self.presentViewController(vc, animated: true, completion: nil)
Use like this
var moveToNextVC:ViewController = self.storyboard?.instantiateViewControllerWithIdentifier("myViewId") as! ViewController
self.presentViewController(moveToNextVC, animated: true, completion: nil)
Remember set StoryboardID Identify 'myViewId' in File Inspector for your viewcontroller

Resources