Unable to retrieve view controller with NSProgressIndicator programatically - ios

I am trying to retrieve the actual view controller and call a method to change the ProgressIndicator.
I have the following function in my AppDelegate
func applicationDidFinishLaunching(_ aNotification: Notification) {
let main = NSStoryboard(name: "Main", bundle: Bundle.main)
let vc = main.instantiateController(withIdentifier: "Installing") as! ViewController
vc.incrementBar(number: 20)
}
The incrementBar function is as follows
#IBOutlet weak var progressView: NSProgressIndicator!
public func incrementBar(number: Double){
if(self.progressView != nil){
print(number)
self.progressView.increment(by: number)
}
}
Just to be sure. I can easily call this function from viewDidLoad() or viewDidAppear() but as soon as i try to receive the actual controller it tells me that progressView is nil

Related

View Controller not loading via instantiateViewController function even with correct identifier

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.

Swift: using delegates to send data to another view controller

How do I use delegates to send data to another view controller and then display it in the collection view? My problem is with moving the array across using delegates.
Below is an example of what I am working on.
When I use usersList in the ThirdViewController, I get an error that says 'Unexpectedly found nil while implicitly unwrapping an Optional value'
protocol ExampleDelegate {
func delegateFunction(usersArray: Array<User>)
}
class ViewController: UIViewController {
private var model: Users = ViewController.createAccount()
var exampleDelegate: ExampleDelegate?
#IBAction func ShowUsers(_ sender: UIButton) {
let ShowUsersVC = storyboard?.instantiateViewController(identifier: "ThirdViewController") as! ThirdViewController
var userList: Array<User> = model.listOfUsers
exampleDelegate?.delegateFunction(usersArray: userList )
present(ShowUsersVC, animated: true)
}
}
class ThirdViewController: UIViewController {
#IBOutlet weak var collectionView: UICollectionView!
var usersList: Array<User>!
override func viewDidLoad() {
super.viewDidLoad()
let GetUsersVC = storyboard?.instantiateViewController(identifier: "ViewController") as! ViewController
GetUsersVC.showMomentsDelegate = self
collectionView.dataSource = self
collectionView.delegate = self
}
}
extension ThirdViewController: ExampleDelegate {
func delegateFunction(usersArray: Array<User>)
usersList = usersArray
}
You don't need delegates in this case. You are sending data forwards, so just do it like this:
class ViewController: UIViewController {
private var model: Users = ViewController.createAccount()
var exampleDelegate: ExampleDelegate?
#IBAction func showUsers(_ sender: UIButton) {
let showUsersVC = storyboard?.instantiateViewController(identifier: "ThirdViewController") as! ThirdViewController
var userList: Array<User> = model.listOfUsers
showUsersVC.usersList = userList /// pass the data!
present(showUsersVC, animated: true)
}
}
Also in Swift you should lowercase objects like userList, as well as functions like showUsers.

View controller's data changes on 2nd attempt

Hey my code changes data in another view controller on 2nd attempt on 1st just showing default values
Code inside button
#IBAction func check(_ sender: Any) {
makeRequest()
let fin = UIStoryboard(name: "FinalViewController", bundle: nil)
let pop = fin.instantiateInitialViewController()! as! FinalViewController
pop.img = icon
pop.state = state
pop.fail = failed
self.present(pop, animated: true)
}
Code inside 2nd view controller
class FinalViewController: UIViewController {
#IBOutlet weak var weathure_icon: UIImageView!
#IBOutlet weak var status: UILabel!
var fail = false
var img = ""
var state = ""
override func viewDidLoad() {
if fail == false{
super.viewDidLoad()
status.text = state
weathure_icon.image = UIImage(named: img+".png")
}
}
Please check three things in your code inside the button action.
Please cross-check, is makeRequest() asynchronous request??
is icon, state and failed parameters request coming from makeRequest() method, in this case you need to handle request data on main thread.
Please replace following in your code:
This
let fin = UIStoryboard(name: "FinalViewController", bundle: nil)
let pop = fin.instantiateInitialViewController()! as! FinalViewController
With
let fin = UIStoryboard(name: "STORYBOARD_NAME", bundle: nil)
let pop = fin.instantiateInitialViewController(identifier: "FinalViewController")! as! FinalViewController
Hope this will help you and make success with your implementation :)

Nil when transferring data from TabbarController to ViewController

I can’t understand what the mistake is,
an ordinary user should register, provided that everything is successful, the current user will show on TabBarController, and if you want him to convert to print("\(currentUser)"), then everything is fine. this user's protocol
Here I output to the console, everything is fine
import UIKit
class MainTabBarViewController: UITabBarController {
var currentUser: MUser = MUser(username: "fdff",
usersurname: "dfdf",
phone: "dffd",
sex: "dfb",
avatarStringURL: "fgf",
id: "gf",
bithDate: "fggf")
override func viewDidLoad() {
super.viewDidLoad()
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let messageVC = storyboard.instantiateViewController(identifier: "MessageVC") as! MessageVC
messageVC.currentUser = currentUser
print("\(currentUser)")
}
}
but you see, I pass it on and in this controller the nil issues
import UIKit
import FirebaseFirestore
class MessageVC: UITableViewController {
var chat = [MChat]()
var currentUser: MUser!
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print(chat[indexPath.row])
print("\(currentUser)") // return nil
let chatsVC = ChatsViewController(user: currentUser, chat: chat[indexPath.row])
navigationController?.pushViewController(chatsVC, animated: true)
}
}
Can anyone explain what I'm doing wrong?
Solution
Try to instantiate the MessageVC from the storyboard and then pass the data to it from the TabBarController.
Hold the reference of MessageVC globally outside ViewDidLoad and use it for navigation.
Example
class MainTabBarViewController: UITabBarController {
var currentUser: MUser = MUser(username: "fdff",
usersurname: "dfdf",
phone: "dffd",
sex: "dfb",
avatarStringURL: "fgf",
id: "gf",
bithDate: "fggf")
// Declare Message VC instance
var messageVC : MessageVC!
override func viewDidLoad() {
super.viewDidLoad()
// Instantiate from Storyboard
let storyboard = UIStoryboard(name: "Main", bundle: nil)
messageVC = storyboard.instantiateViewController(identifier: "VCIdentifier")
messageVC.currentUser = currentUser
print("\(currentUser)")
}
}
Update: Access Child ViewController from TabBarController
func accessMessageVC() {
// Use your viewcontroller index.
let vc = self.viewControllers![2] as! MessageVC
messageVC.currentUser = currentUser
}
Call this method from TabBarController's ViewDidLoad

How to encapsulate an UIViewController (like UIAlertController) in Swift?

I have a ViewController in my Storyboard which works like an alert (with a title, a message, and two buttons).
I would like to encapsulate it to be able to use it anywhere in my code, like this :
let alert = CustomAlertViewController(title: "Test", message: "message de test.", view: self.view, delegate: self)
self.present(alert, animated: false, completion: nil)
My problem is that the IBOutlets are not initialised...
My CustomAlertViewController :
public protocol CustomAlertProtocol {
func alertAccepted()
}
class CustomAlertViewController: UIViewController {
var delegate :CustomAlertProtocol? = nil
var parentView :UIView?
var blurScreenshot :SABlurImageView?
var alertTitle :String? = nil
var alertMessage :String? = nil
#IBOutlet weak var oAlertView: UIView!
#IBOutlet weak var oAlertTitle: UILabel!
#IBOutlet weak var oAlertMessage: UILabel!
//MARK: - Main
public convenience init(title: String?, message: String?, view: UIView, delegate: CustomAlertProtocol) {
self.init()
self.alertTitle = title
self.alertMessage = message
self.delegate = delegate
self.parentView = view
}
override func viewDidLoad() {
oAlertTitle.text = self.alertTitle
oAlertMessage.text = self.alertMessage
}
#IBAction func onAcceptButtonPressed(_ sender: AnyObject) {
delegate?.alertAccepted()
}
}
Set the Custom Class property of your View Controller to CustomAlertViewController
and Storyboard ID to whatever you want - e.g. CustomAlertViewControllerIdentifier in the Identity Inspector of the InterfaceBuilder.
And then instantiate it like following:
let storyboard = UIStoryboard(name: "Main", bundle: NSBundle.mainBundle())
guard let vc = storyboard.instantiateViewControllerWithIdentifier("CustomAlertViewControllerIdentifier") as? CustomAlertViewController else {
return
}
edit:
You can then put that code in a class function like:
extension CustomAlertViewController {
class func instantiateFromStoryboard(title: String?, message: String?, view: UIView, delegate: CustomAlertProtocol) -> CustomAlertViewController {
let storyboard = UIStoryboard(name: "Main", bundle: NSBundle.mainBundle())
let vc = storyboard.instantiateViewControllerWithIdentifier("CustomAlertViewControllerIdentifier") as! CustomAlertViewController
vc.title = title
vc.message = message
vc.view = view
vc.delegate = delegate
return vc
}
}
and then use like:
let myCustomAlertViewController = CustomAlertViewController.instantiateFromStoryboard(title: "bla", ...)

Resources