I'm just learning XCode and now I have the following problem, I've tried a few things but I can't get any further at this point, does anyone have an idea of what this could be.
I have two ViewControllers. With the first ViewController you have the possibility to open a popup for user input via a button (second ViewControler). After entering the user, you can save the user with a save button and you should get back to the main page. Then I always get the error
"Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[PwGen.ViewControllerUser tfUser:]: unrecognized selector sent to instance "
///////////////////////////Button save
#IBAction func btnConfirm(_ sender: UIButton)
{
save()
let story = UIStoryboard(name: "Main", bundle: nil)
let controller = story.instantiateViewController(withIdentifier: "ViewController") as! ViewController
controller.modalPresentationStyle = .fullScreen
self.present(controller, animated: false, completion: nil)
}
///////////////////////////function save
func save()
{
let strEingabe = tfUser.text
let defaults = UserDefaults.standard
defaults.set(strEingabe, forKey: "customTextUser")
defaults.synchronize()
let strtest = defaults.string(forKey: "customTextUser")
print(strtest)
}
Thanks a lot
Hi guys,
I've tried a few more things, but without success
Here is the code of my second ViewControll. If I don't enter anything in the "tfUser" text field, everything works as desired and the first view controller is opened and the code of the first view is processed. However, if you enter something in "tfUser", the value is saved, the first ViewController is opened and then crashes, although the same code is processed as if you left "tfUser" empty
i don't know why its working when "tfUser" is empty to and string in "tfUser".
import UIKit
class ViewControllerUser: UIViewController {
#IBOutlet weak var tfUser: UITextField!
override func viewDidLoad()
{
super.viewDidLoad()
// Do any additional setup after loading the view.
}
//Button abort
#IBAction func btnBack(_ sender: UIButton)
{
tfUser.text = ""
let vc = storyboard?.instantiateViewController(withIdentifier: "ViewController") as! ViewController
vc.modalPresentationStyle = .fullScreen
present(vc, animated: false)
}
//Button confirm
#IBAction func btnConfirm(_ sender: UIButton)
{
save()
let vc = storyboard?.instantiateViewController(withIdentifier: "ViewController") as! ViewController
vc.modalPresentationStyle = .fullScreen
present(vc, animated: false)
}
//function save
func save()
{
let strEingabe = ("\(tfUser.text ?? "")")
let defaults = UserDefaults.standard
defaults.set(strEingabe, forKey: "customTextUser")
tfUser.text = ""
}
}
Related
Goal: In a separate storyboard that is loaded via a storyboard reference in the main.storyboard, in a pageViewController acting as the initial view controller, I want to initialize an array object of viewControllers via the function .instantiateViewController(identifier:).
Issue: The last viewController I'm trying to instantiate as a constant is not loading. The error - *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Could not load the scene view controller for identifier 'FinalVC''"
All other viewControllers in this storyboard load fine. This last view controller has a correct custom class linked and a unique storyboard identifier.
Debugging: I've created a breakpoint where this view controller is instantiated and noticed in the debugging console all other view controller objects load as "BillyCues.repeatViewController + unique identification number" while this last vc loads as "UIViewController + 0x000000000000000". It's almost as if this vc is not a part of the app bundle or referenced correctly but it's there when I search in the directory.
Debugging console screen
Things I've tried that did not work:
Check to see if another vc has the same identifier
Clean the build folder
Check "Use Storyboard ID" in the identity inspector
let finalVC = storyBoard.instantiateViewController(identifier: "FinalVC") as! FinalViewController
Restart Xcode
Create a brand new view controller with a different storyboard identifier using the same custom class
Removed all connections from buttons and labels in the last vc
Made sure all storyboard references in main.storyboard has the correct storyboard linked
Conclusion: All my googling has led to other developers encountering the error about NIBs or tableviews not necessarily a view controller. If my vc has a correct custom class and unique identifier the error should not occur. If anyone can offer guidance I'd appreciate it; I'm dumbfounded.
I hope I've asked for help in an appropriate structure but please let me know if more code or screenshots are needed.
PageViewController Code
import UIKit
class LauncherViewController: UIPageViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.setViewControllers([viewControllerList[0]], direction: .forward, animated: false, completion: nil)
// Do any additional setup after loading the view.
}
private var viewControllerList: [UIViewController] = {
let storyBoard = UIStoryboard.cueCreation
let firstVC = storyBoard.instantiateViewController(identifier: "CueNameVC")
let secondVC = storyBoard.instantiateViewController(identifier: "DueDateVC")
let thirdVC = storyBoard.instantiateViewController(identifier: "IconVC")
let fourthVC = storyBoard.instantiateViewController(identifier: "IconColorVC")
let fifthVC = storyBoard.instantiateViewController(identifier: "RepeatVC")
let finalVC = storyBoard.instantiateViewController(identifier: "FinalVC") as! FinalViewController
return [firstVC, secondVC, thirdVC, fourthVC, fifthVC, finalVC]
}()
var selectedReminderBill: CueObject?
public var currentIndex = 0
static var cueName: String = ""
static var cueDate: Date = Date()
static var cueIcon: Data = Data()
static var iconColor:String = "14CC7F"
static var repeatMonthly: Bool = false
// Navigation button functions below to move to the next or previous page
func pushNext() {
if currentIndex + 1 < viewControllerList.count {
self.setViewControllers([self.viewControllerList[self.currentIndex + 1]], direction: .forward, animated: true, completion: nil)
currentIndex += 1
}
}
func pullBack() {
print(currentIndex)
if currentIndex - 1 < viewControllerList.count {
self.setViewControllers([self.viewControllerList[self.currentIndex-1]], direction: .reverse, animated: true, completion: nil)
currentIndex -= 1
}
}
}
FinalViewController Code
import UIKit
import UserNotifications
import RealmSwift
class FinalViewController: UIViewController {
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
cueName.text = LauncherViewController.cueName
dueDate.text = CueLogic.convertPaymentDateToString(for: LauncherViewController.cueDate)
iconBackgroundView.backgroundColor = colorLogic.colorWithHexString(hexString: LauncherViewController.iconColor)
cueIcon.image = UIImage(data: LauncherViewController.cueIcon)
repeatsMonthly.text = repeatMonthlyToString
}
override func viewDidLoad() {
super.viewDidLoad()
cueName.layer.cornerRadius = 15
cueName.clipsToBounds = true
iconBackgroundView.layer.cornerRadius = 20
iconBackgroundView.clipsToBounds = true
dueDate.layer.cornerRadius = 15
dueDate.clipsToBounds = true
repeatsMonthly.layer.cornerRadius = 15
repeatsMonthly.clipsToBounds = true
backButton.layer.cornerRadius = 15
backButton.clipsToBounds = true
saveButton.layer.cornerRadius = 15
saveButton.clipsToBounds = true
// Do any additional setup after loading the view.
}
let colorLogic = ColorLogic()
let realm = try! Realm()
weak var delegate: HomeScreenDelegate?
var launcher = LauncherViewController()
var repeatMonthlyToString: String {
get {
if LauncherViewController.repeatMonthly == true {
return "Repeats Monthly: Yes"
} else {
return "Repeats Monthly: No"
}
}
}
#IBOutlet var cueName: UILabel!
#IBOutlet var dueDate: UILabel!
#IBOutlet var saveButton: UIButton!
#IBOutlet var backButton: UIButton!
#IBOutlet var iconBackgroundView: UIView!
#IBOutlet var cueIcon: UIImageView!
#IBOutlet var repeatsMonthly: UILabel!
#IBAction func dismissButtonTapped(_ sender: Any) {
self.dismiss(animated: true, completion: nil)
}
#IBAction func backButtonTapped(_ sender: Any) {
if let pageController = parent as? LauncherViewController {
pageController.pullBack()
}
}
#IBAction func saveButtonTapped(_ sender: Any) {
// Request authorization from the user to allow notifications
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound], completionHandler: {success, error in
if success {
// schedule test
} else if let error = error {
print("error occured \(error)")
}
})
let newCue = CueObject()
let launcherVC = LauncherViewController.self
newCue.name = launcherVC.cueName
newCue.paymentDate = launcherVC.cueDate
newCue.icon = launcherVC.cueIcon
newCue.iconColor = launcherVC.iconColor
newCue.repeatsMonthly = launcherVC.repeatMonthly
NotificationLogic.scheduleLocalAlertForBill(named: newCue.name, due: newCue.paymentDate, repeatsMonthly: newCue.repeatsMonthly)
saveToDB(for: newCue)
delegate?.loadCuesFromRealm()
self.dismiss(animated: true, completion: nil)
}
func saveToDB(for cue: CueObject) {
do {
try realm.write({
realm.add(cue)
})
} catch {
print("Error - \(error)")
}
}
}
protocol HomeScreenDelegate: AnyObject {
func loadCuesFromRealm()
}
Extension I wrote in another viewController
extension UIStoryboard {
static let onboarding = UIStoryboard(name: "Onboarding", bundle: nil)
static let main = UIStoryboard(name: "Main", bundle: nil)
static let cueCreation = UIStoryboard(name:"CueCreation", bundle: nil)
}
Identity Inspector
Main Storyboard References
I'd do a few things as part of cleanup to start debugging the actual issue. In the storyboard extension, I'd rather use a static function to reference the view controller.
extension UIStoryboard {
class func createFinalVC() -> FinalViewController? {
return UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "FinalVC") as? FinalViewController)
}
}
And for implementing it, I'd use in the view controller presenting FinalViewController:
private func createCreateFinalVC() -> FinalViewController? {
return UIStoryboard.createFinalVC()
}
And finally pushing it into the view,
if let finalVC = createCreateFinalVC() {
yourNavController?.pushViewController(finalVC, animated: true)
}
Solution
I began a process of elimination and started to comment out all of the code in my FinalVC class. I learned that this line of code var launcher = LauncherViewController() was triggering the crash.
Given my limited beginner knowledge I don't know why this would cause a crash; I can only assume that Xcode was trying to initialize two LauncherViewControllers with identical identifier numbers or something along those lines.
I'm trying to make a function for my navigation without having to type the exact same lines over and over again.
Trying to do so results into an error: "Use of undeclared type 'viewController'"
Am I doing this completely wrong, should I just place these 4 lines on every button just with different identifier and viewController?
func navigateTo(identifier:String, viewController:UIViewController) {
let newVC = storyboard?.instantiateViewController(withIdentifier: identifier) as! viewController
newVC.modalPresentationStyle = .fullScreen
newVC.modalTransitionStyle = .flipHorizontal
self.present(newVC, animated: true, completion: nil)
}
#IBAction func btnOneTapped(_ sender: Any) {
navigateTo("myVC", MyViewController)
}
Make sure you provide correct identifier...below code works perfectly.
Your Error -> Trying to do so results into an error: "Use of undeclared type 'viewController'"
In this there is a typo mistake for ViewController i.e you are trying this - viewController
Also always try to do Optional-Binding instead to force-unwarpping it may cause crash in your app.
func navigateTo(identifier:String, viewController:UIViewController) {
if let newVC = storyboard?.instantiateViewController(withIdentifier: identifier) {
newVC.modalPresentationStyle = .fullScreen
newVC.modalTransitionStyle = .flipHorizontal
self.present(newVC, animated: true, completion: nil)
}
}
#IBAction func confirmBtn(_ sender: UIButton) {
navigateTo(identifier: "myVC", viewController: MyViewController())
}
You are passing an instance of UIViewController and trying to cast the UIViewController to it in the next line. Modify your function to take in ViewController.Type as parameter like this:
func navigateTo<ViewController: UIViewController>(identifier: String, viewController: ViewController.Type) {
let newVC = storyboard?.instantiateViewController(withIdentifier: identifier) as! ViewController
newVC.modalPresentationStyle = .fullScreen
newVC.modalTransitionStyle = .flipHorizontal
self.present(newVC, animated: true, completion: nil)
}
#IBAction func btnOneTapped(_ sender: Any) {
navigateTo(identifier: "myVC", viewController: MyViewController.self)
}
Thank you guys, I've got it working like so:
func navigateToVC(identifier:String, viewController:ViewController.Type) {
let newVC = storyboard?.instantiateViewController(withIdentifier: identifier) as! ViewController
newVC.modalPresentationStyle = .fullScreen
newVC.modalTransitionStyle = .flipHorizontal
self.present(newVC, animated: true, completion: nil)
}
#IBAction func btnOneTapped(_ sender:Any) {
navigateToVC(identifier: "myVC", viewController: MyViewController.self)
}
I am facing very weird error unexpectedly found nil while unwrapping an optional value navigationcontroller.
I have two viewControllers which has main function is to scan bar code and sets value in textField on PreBarCodeViewController. Second viewController is the barcodeViewController which scan. According to perspective user either manually input value or scan to fetch bar code. When I go for manual input navigation controller works fine. But once I click for scan and gets value in a textField and press ok button it won't navigate. Even if I click cross button it gives me nil error.
Updated: included barcode viewcontroller open on button tap.
PreBarcodeViewController: two buttons Back and Accept
#IBAction func toBarcode(_ sender: Any) {
let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let newViewController = storyBoard.instantiateViewController(withIdentifier: "BarcodeViewController") as! BarcodeViewController
present(newViewController, animated: true, completion: nil)
}
#IBAction func onClickedBackArrow(_ sender: Any) {
self.navigationController!.popViewController(animated: true)
}
#IBAction func onClickedAccept(_ sender: Any) {
let value = textField.text ?? String(describing: txtValue)
bardelegate?.listFunc(listValue: value )
self.navigationController?.popViewController(animated: true)
}
BarcodeViewController: When I get the value post to back.
if url == decodedURL {
let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let newViewController = storyBoard.instantiateViewController(withIdentifier: "PreBarcodeViewController") as! PreBarcodeViewController
let str2 = String(url)
newViewController.txtValue = str2
present(newViewController, animated: true, completion: nil)
}
When you open with present() view controller then used the
dismiss()
method to back to previous screen.
popViewController()
only used when you navigate with navigation controller please check this.
I am a beginner in iOS.
I have a problem that I made a class named ModalViewController. To make this as a common class, I didn't give any text to the textView in this class. So I tried to change the text when I present this viewController.
But I am getting an error. How can I fix it?
In addition, how can I change the margin value in text view?
Main.storyboard
MainViewController.swift
import UIKit
var modalview : ModalViewController!
class ViewController: UIViewController {
...
#IBAction func Onclick(_ sender: Any) {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let myAlert = storyboard.instantiateViewController(withIdentifier: "ModalViewController")
myAlert.modalPresentationStyle = UIModalPresentationStyle.overCurrentContext
myAlert.modalTransitionStyle = UIModalTransitionStyle.crossDissolve
modalview.modalCustomAlert.text = "test test test text" // Thread 1: Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value
self.present(myAlert, animated: true, completion: nil)
}
ModalViewController.swift
import Foundation
import UIKit
class ModalViewController : UIViewController {
#IBOutlet weak var modalCustomAlert: UITextView!
#IBOutlet weak var cancelButton: UIButton!
#IBOutlet weak var okButton: UIButton!
#IBAction func cancelPress(_ sender: Any) {
}
#IBAction func okPress(_ sender: Any) {
}
override func viewDidLoad() {
super.viewDidLoad()
modalCustomAlert.layer.cornerRadius = 8
}
#IBAction func modalbutton(_ sender: Any) {
}
}
Edited start
I tried to assign a value but there was no change in the error.
var modalview = ModalViewController()
...
#IBAction func Onclick(_ sender: Any) {
...
modalview.modalCustomAlert.text = "test test test text" // Thread 1: Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value
}
Edited TWO start
I've tried this already. But when I saw the answer from #PGDev, I tried it again, but it showed the same error.
#IBAction func Onclick(_ sender: Any) {
...
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let myAlert = storyboard.instantiateViewController(withIdentifier: "ModalViewController") as! ModalViewController
myAlert.modalPresentationStyle = .overCurrentContext
myAlert.modalTransitionStyle = .crossDissolve
myAlert.modalCustomAlert.text = "test test test text" // Thread 1: Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value
self.present(myAlert, animated: true, completion: nil)
}
Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value
modalview.modalCustomAlert.text = "test test test text"
The exception is because either modalview is nil or modalCustomAlert is nil.
1. You've created modalview as implicitly unwrapped optional like,
var modalview : ModalViewController!
Check if you've assigned any value to modalview before accessing it. If you haven't this will result in crash.
2. Next, you have created an outlet of modalCustomAlert,
#IBOutlet weak var modalCustomAlert: UITextView!
This is also an implicitly unwrapped optional. Check if the outlet is connected properly. If it isn't it will raise the runtime exception.
If an implicitly unwrapped optional is nil and you try to access its
wrapped value, you’ll trigger a runtime error. The result is exactly
the same as if you place an exclamation mark after a normal optional
that doesn’t contain a value.
Edit-1:
var modalview = ModalViewController()
The above code won't connect the outlets in ModalViewController. That's the reason modalCustomAlert is nil and result in exception.
Create modalview using storyboard like,
let modalview = storyboard.instantiateViewController(withIdentifier: "ModalViewController")
One question though. What's the reason to create modalview and myAlert separately if they both are of type ModalViewController?
Edit-2:
I don't think there is even a need to create modalview. Simply use myAlert view at the line where you're getting the exception. So the code for ViewController goes like,
class ViewController: UIViewController {
//....
#IBAction func Onclick(_ sender: Any) {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let myAlert = storyboard.instantiateViewController(withIdentifier: "ModalViewController") as! ModalViewController
myAlert.modalPresentationStyle = .overCurrentContext
myAlert.modalTransitionStyle = .crossDissolve
myAlert.modalCustomAlert.text = "test test test text"
self.present(myAlert, animated: true, completion: nil)
}
}
Edit-3:
Got that. Just didn't realise that you're accessing modalCustomAlert before the outlets are created.
First of all, in ModalViewController create a property text. And in viewDidLoad() add this text as modalCustomAlert.text, i.e.
class ModalViewController : UIViewController {
//rest of the code....
var text: String? //here....
override func viewDidLoad() {
super.viewDidLoad()
modalCustomAlert.layer.cornerRadius = 8
self.modalCustomAlert.text = text //here....
}
}
Now, when creating alertView, replace
myAlert.modalCustomAlert.text = "test test test text"
with
myAlert.text = "test test test text"
Please add one new variable String in Your ModalViewController
class ModalViewController : UIViewController {
var objTextViewString:String = ""
override func viewDidLoad() {
super.viewDidLoad()
self.modalCustomAlert.text = self.objTextViewString
}
}
On ModelViewController Present Please pass String On added String Variable..That's It..!!
class ViewController: UIViewController {
//....
#IBAction func Onclick(_ sender: Any) {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let myAlert = storyboard.instantiateViewController(withIdentifier: "ModalViewController") as! ModalViewController
myAlert.modalPresentationStyle = .overCurrentContext
myAlert.modalTransitionStyle = .crossDissolve
myAlert.objTextViewString = "test test test test"
self.present(myAlert, animated: true, completion: nil)
}
}
I recently started to learn swift and it has been pretty good so far. Currently I'm having an issue trying to pass data between view controllers. I managed to figure out how to programmatically navigate between two view controllers using a navigation controller. Only problem is now I'm having a hard time trying to figure out how to pass three string entered by the user (for json api) to the next view.
Here's my current attempt. Any help is much appreciated!
ViewController:
/* Get the status code of the connection attempt */
func connection(connection:NSURLConnection, didReceiveResponse response: NSURLResponse){
let status = (response as! NSHTTPURLResponse).statusCode
//println("status code is \(status)")
if(status == 200){
var next = self.storyboard?.instantiateViewControllerWithIdentifier("SecondViewController") as! SecondViewController
self.presentViewController(next, animated: false, completion: nil)
}
else{
RKDropdownAlert.title("Error", message:"Please enter valid credentials.", backgroundColor:UIColor.redColor(), textColor:UIColor.whiteColor(), time:3)
drawErrorBorder(usernameField);
usernameField.text = "";
drawErrorBorder(passwordField);
passwordField.text = "";
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
let navigationController = segue.destinationViewController as! UINavigationController
let newProjectVC = navigationController.topViewController as! SecondViewController
newProjectVC.ip = ipAddressField.text
newProjectVC.username = usernameField.text
newProjectVC.password = passwordField.text
}
SecondViewController:
import UIKit
class SecondViewController: UIViewController {
var ip:NSString!
var username:NSString!
var password:NSString!
override func viewDidLoad() {
super.viewDidLoad()
println("\(ip):\(username):\(password)")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
The method prepareForSegue is called when your app's storyboard performs a segue (a connection that you create in storyboards with Interface Builder). In the code above though you are presenting the controller yourself with presentViewController. In this case, prepareForSegue is not fired. You can do your setup right before presenting the controller:
let next = self.storyboard?.instantiateViewControllerWithIdentifier("SecondViewController") as! SecondViewController
next.ip = ipAddressField.text
next.username = usernameField.text
next.password = passwordField.text
self.presentViewController(next, animated: false, completion: nil)
You can read more about segue here
Updated syntax for Swift 3:
let next = self.storyboard?.instantiateViewController(withIdentifier: "SecondViewController") as? SecondViewController
next.ip = ipAddressField.text
next.username = usernameField.text
next.password = passwordField.text
self.present(next, animated: true, completion: nil)