当应用程序进行背景时,如何调用方法并更改某些活动,例如移动的时间或日期,然后进入前景(应用程序活动模式)。
然后我想在uiviewController类中调用方法
firstViewController类方法。
-(void)refreshItems{
// Your item refresh code.
}
在ViewController中添加以下代码
override func viewDidLoad() {
super.viewDidLoad()
//Mark:- application move to bckground
let backgorundNotificationCenter = NotificationCenter.default
notificationCenter.addObserver(self, selector:#selector(appMovedToBackground), name: UIApplication.willResignActiveNotification, object: nil)
//Mark:- application move to foreground
let foregroundNotificationCenter = NotificationCenter.default
notificationCenter.addObserver(self, selector:#selector(appMovedToForeground),name: UIApplication.willEnterForegroundNotification, object: nil)
}
//Mark:- background method implementation
@objc func appMovedToBackground() {
print("App moved to background!")
}
//Mark:- foreground method implementation
@objc func appMovedToForeground() {
print("App moved to foreground!")
}
我想你只需要
[[NSNotificationCenter defaultCenter] addobserver:self Selector:@selector(RefReshitems)名称:uiapplicationdidbecomeactivenotification对象:nil];
检查此代码(如果FirstViewController是Window的rootviewController,则在AppDelegate中使用FirstViewController的实例,并检查NULL)
)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];
}
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];