Search code examples
iosswiftmemory-managementalertview

"applicationDidReceiveMemoryWarning" memory warning alert in AppDelegate swfit4.2?


We have handled the memory warning alert in AppDelegate class in our application. It navigates to the home screen when it called "applicationDidReceiveMemoryWarning" function but the alert is not shown? I will add my code below. Can anyone help me?

func applicationDidReceiveMemoryWarning(_ application: UIApplication) {
    resetWhenMemoryWarningPresented()

}

// To get the current view controller
func getCurrentViewController(_ vc: UIViewController) -> UIViewController? {
    if let presentViewControllers = vc.presentedViewController {
        return getCurrentViewController(presentViewControllers)
    }
    else if let splitViewControllers = vc as? UISplitViewController, splitViewControllers.viewControllers.count > 0 {
        return getCurrentViewController(splitViewControllers.viewControllers.last!)
    }
    else if let navigationControllers = vc as? UINavigationController, navigationControllers.viewControllers.count > 0 {
        return getCurrentViewController(navigationControllers.topViewController!)
    }
    else if let tabBarViewControllers = vc as? UITabBarController {
        if let selectedViewController = tabBarViewControllers.selectedViewController {
            return getCurrentViewController(selectedViewController)
        }
    }
    return vc
}

public func resetWhenMemoryWarningPresented() {
    guard let rootViewControllers = self.window?.rootViewController else {
        return
    }
    if let viewControllers = getCurrentViewController(rootViewControllers) {
        weak var controller = viewControllers
        print("VIEWCONTROLLER NAME \(String(describing: controller))")
        let window = UIApplication.shared.keyWindow!
        let storyboard = UIStoryboard(name: "Main", bundle: Bundle.main)
        weak var viewController = storyboard.instantiateViewController(withIdentifier: "Navigation") as? UINavigationController
        window.rootViewController = viewController
        window.makeKeyAndVisible()
        viewController?.showConfirmAlert(title: "Memory Warning", message: "Your phone is running on low memory. Please close other apps before continuing or you may experience unexpected behaviour", buttonTitle: "OK", buttonStyle: .default) { (action) in
            controller = nil
            viewController = nil
        }
    }
}

Solution

  • You shouldn't ask the user to close some apps but you should clear variables in the didReceiveMemoryWarning method. Take a look at this StackOverflow post: How to implement didReceiveMemoryWarning?