Segue not getting called programmatically only if button pressed

15 Views Asked by At

I am trying to call a segue if a certain condition is met or via a button press. When the programme loads if vehicles.count == 0 it prints("going to new vehicle") but doesn't perform the segue. However if I press the button it does work. I have tried "shouldPerformSegue(withIdentifier: "goToNewVehicle", sender: nil) and performSegue(withIdentifier: "goToNewVehicle", sender: self)" and

"self.selectVehicle(self)"

but that's as far as it goes. Here is the code. Obviously I am new to all this. Any help appreciated. thank you

override func viewDidLoad() {
    super.viewDidLoad()
    
    checkForAndLoadVehicles()
    
}


//MARK: Segues
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    let destinationVC = segue.destination as! NewVehicleController
}

@IBAction func selectVehicle(_ sender: Any) {
    print("button pressed")
    performSegue(withIdentifier: "goToNewVehicle", sender: self)

}

//MARK: Check for and Load vehicles
func checkForAndLoadVehicles() {
    guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
        return
    }
    let managedContext = appDelegate.persistentContainer.viewContext
    let vehicleFetchRequest = NSFetchRequest<NSManagedObject>(entityName: "Vehicle")
    do {
        vehicles = try managedContext.fetch(vehicleFetchRequest)
        print(vehicles.count)
    } catch let error as NSError {
        print("Could not fetch. \(error), \(error.userInfo)")
    }
    if vehicles.count == 0 {
        print("going to new vehicle")
        performSegue(withIdentifier: "goToNewVehicle", sender: self)
        
        self.selectVehicle(self)


    } 

I have tried both the options shown to call the segue but neither work

0

There are 0 best solutions below