当应用程序进入后台并进入前台时调用UIViewController方法

问题描述:

如何在应用程序进入后台并更改某些活动(如移动时间或日期)和前台(应用程序活动模式)时调用方法。当应用程序进入后台并进入前台时调用UIViewController方法

然后我想调用的UIViewController类

FirstViewController类方法的方法。

-(void)refreshItems{ 
// Your item refresh code. 
} 

检查这个代码(如果FirstViewController是窗口的RootViewController的其他人采取FirstViewController的实例中的AppDelegate和检查空)

func applicationDidEnterBackground(_ application: UIApplication) { 
    if let appDelegate = UIApplication.shared.delegate as? AppDelegate, 
     let controller = appDelegate.window?.rootViewController as? FirstViewController { 
     controller.refreshItems() 
    } 
} 

func applicationWillEnterForeground(_ application: UIApplication) { 
    if let appDelegate = UIApplication.shared.delegate as? AppDelegate, 
     let controller = appDelegate.window?.rootViewController as? FirstViewController { 
     controller.refreshItems() 
    } 
} 

Objective-C的

- (void)applicationDidEnterBackground:(UIApplication *)application { 
    AppDelegate *appDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate; 
    FirstViewController *controller = (FirstViewController*)[[appDelegate window] rootViewController]; 
    [controller refreshItems]; 
} 


- (void)applicationWillEnterForeground:(UIApplication *)application { 
    AppDelegate *appDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate; 
    FirstViewController *controller = (FirstViewController*)[[appDelegate window] rootViewController]; 
    [controller refreshItems]; 
} 
+0

我需要Objective-C – kiran

我猜你只需要

[[NSNotificationCenter defaultCenter] addObserver:self selector: @selector(refreshItems)name:UIApplicationDidBecomeActiveNotification object:nil];

you have set notification in appDelegate class 

    - (void)applicationWillEnterForeground:(UIApplication *)application { 

     [[NSNotificationCenter defaultCenter] postNotificationName:@"forground"  object:nil]; 

    } 

and add observer to your viewcontroller class viewdidload() methos 

    [[NSNotificationCenter defaultCenter] addObserver:self 
               selector:@selector(showMainMenu:) 
                name:@"refreshItems" object:nil];