Search code examples
xcodeswiftswift2ios9xcode7

Use of unresolved identifier 'checkOrientation' Swift


When I Try Type Return My Func I Get This Error In AppDalgate.Swift

AppDalgate.Swift

  func application (application: UIApplication, supportedInterfaceOrientationsForWindow window: UIWindow?) -> UIInterfaceOrientationMask {
        return checkOrientation(self.window?.rootViewController)

    }

This Code For ViewController.Swift

  func checkOrientation(viewController:UIViewController?)-> Int{

        if(viewController == nil){

            return Int(UIInterfaceOrientationMask.All.rawValue)//All means all orientation

        }else if (viewController is LoginViewController){

            return Int(UIInterfaceOrientationMask.Portrait.rawValue)//This is sign in view controller that i only want to set this to portrait mode only

        }else{

            return checkOrientation(viewController!.presentedViewController)
        }
    }

Solution

  • Your App Delegate does not have access to functions in your View Controller. If you want to achieve this, one option would be to add a variable to the AppDelegate and set it equal to an instantiated ViewController Like so:

    //Add this to your AppDelegate Outside of the methods.
    var vc = ViewController()
    

    After doing this, you can access the ViewController's methods from the AppDelegate like so:

    //Inside a method of AppDelegate
    //Replace ... with your parameters
    vc.checkOrientation(...)
    

    HOWEVER, keep in mind this is not the same instance of the ViewController class that your app will use when the app has finished launching. So if you try to use a method that references data that is added after the app has launched, it will not work.

    Also, keep in mind that the AppDelegate should be kept as concise as possible for performance reasons.

    Furthermore, you should probably change your checkOrientation function to:

    func checkOrientation(viewController:UIViewController?)-> UIInterfaceOrientationMask {
        if viewController is LoginViewController {
            return UIInterfaceOrientationMask.Portrait
        } else {
            return UIInterfaceOrientationMask.All
        }
    }
    

    Lastly, consider removing checkOrientation entirely and putting its logic in supportedInterfaceOrientationsForWindow. Example:

    func application (application: UIApplication, supportedInterfaceOrientationsForWindow window: UIWindow?) -> UIInterfaceOrientationMask {
       if self.window?.rootViewController is LoginViewController {
          return UIInterfaceOrientationMask.Portrait
       } else {
          return UIInterfaceOrientationMask.All
       }
    }