How to segue programmatically in iOS using Swift

Cover Image for How to segue programmatically in iOS using Swift
Matheus Mello
Matheus Mello
published a few days ago. updated a few hours ago

How to Segue Programmatically in iOS Using Swift 🚀

If you're working on an iOS app and have been wondering how to segue programmatically using Swift, you've come to the right place! 🎉 In this blog post, we'll dive into common issues and provide easy solutions so that you can seamlessly transition between views in your app. Let's get started! 💪

The Context 👀

Imagine you're building an app that uses the Facebook SDK to authenticate users. You've successfully written code to handle session state changes in a separate class called FBManager. Here's a simplified version of your code:

import Foundation

class FBManager {
    class func fbSessionStateChange(fbSession: FBSession!, fbSessionState: FBSessionState, error: NSError?) {
        //.. handle all session states

        FBRequestConnection.startForMeWithCompletionHandler { 
            (conn: FBRequestConnection!, result: AnyObject!, error: NSError!) -> Void in
            
            println("Logged in user: \n\(result)")
            
            let storyboard = UIStoryboard(name: "Main", bundle: NSBundle.mainBundle())
            let loggedInView: UserViewController = storyboard.instantiateViewControllerWithIdentifier("loggedInView") as UserViewController
            
            loggedInView.result = result
            
            //todo: segue to the next view???
        }
    }
}

The Question ❓

You've successfully obtained the user's data, and now you want to segue to the next view from within your FBManager class. But how do you achieve this when you're not in a view controller? 🤔

The Solution 💡

To perform a segue from a class that isn't a view controller, you'll need to access the current view controller and trigger the segue programmatically. Here's how you can do it:

  1. Import the UIKit framework in your FBManager class to access its classes.

import Foundation
import UIKit
  1. Create a UIWindow extension or utility function to find the current view controller. You can add the following extension to your code:

extension UIWindow {
    func getCurrentViewController() -> UIViewController? {
        if let rootViewController = self.rootViewController {
            var currentViewController: UIViewController? = rootViewController
            while let presentedViewController = currentViewController?.presentedViewController {
                currentViewController = presentedViewController
            }
            return currentViewController
        }
        return nil
    }
}
  1. Use the getCurrentViewController() function to get the current view controller and perform the segue programmatically. Replace the //todo: segue to the next view??? line with the following code:

if let currentViewController = UIApplication.sharedApplication().keyWindow?.getCurrentViewController() {
    currentViewController.performSegueWithIdentifier("yourSegueIdentifier", sender: nil)
}

Make sure to replace "yourSegueIdentifier" with the actual identifier of the segue you've set up in your storyboard.

Time to Shine 💫

You're all set! With just a few lines of code, you can now segue programmatically from within your FBManager class. 🎉

Remember, don't be afraid to experiment and explore different possibilities. Adding the ability to programmatically segue is a powerful tool that can enhance the user experience of your app.

Conclusion 🌟

In this blog post, we've learned how to segue programmatically in iOS using Swift. By accessing the current view controller and triggering the segue, we can seamlessly transition between views, even from a class that isn't a view controller. 💪

We hope this guide has been helpful to you! If you have any questions or need further assistance, please don't hesitate to leave a comment below. Happy coding! 😊✨

Did you find this blog post helpful? Share it with your fellow iOS developers and let's make app development even more awesome! 🚀


More Stories

Cover Image for How can I echo a newline in a batch file?

How can I echo a newline in a batch file?

updated a few hours ago
batch-filenewlinewindows

🔥 💻 🆒 Title: "Getting a Fresh Start: How to Echo a Newline in a Batch File" Introduction: Hey there, tech enthusiasts! Have you ever found yourself in a sticky situation with your batch file output? We've got your back! In this exciting blog post, we

Matheus Mello
Matheus Mello
Cover Image for How do I run Redis on Windows?

How do I run Redis on Windows?

updated a few hours ago
rediswindows

# Running Redis on Windows: Easy Solutions for Redis Enthusiasts! 🚀 Redis is a powerful and popular in-memory data structure store that offers blazing-fast performance and versatility. However, if you're a Windows user, you might have stumbled upon the c

Matheus Mello
Matheus Mello
Cover Image for Best way to strip punctuation from a string

Best way to strip punctuation from a string

updated a few hours ago
punctuationpythonstring

# The Art of Stripping Punctuation: Simplifying Your Strings 💥✂️ Are you tired of dealing with pesky punctuation marks that cause chaos in your strings? Have no fear, for we have a solution that will strip those buggers away and leave your texts clean an

Matheus Mello
Matheus Mello
Cover Image for Purge or recreate a Ruby on Rails database

Purge or recreate a Ruby on Rails database

updated a few hours ago
rakeruby-on-railsruby-on-rails-3

# Purge or Recreate a Ruby on Rails Database: A Simple Guide 🚀 So, you have a Ruby on Rails database that's full of data, and you're now considering deleting everything and starting from scratch. Should you purge the database or recreate it? 🤔 Well, my

Matheus Mello
Matheus Mello