我正在尝试使用来自 this example 的代码:
- (void)applicationDidEnterBackground:(UIApplication *)application
{
bgTask = [application beginBackgroundTaskWithName:@"MyTask" expirationHandler:^{
// Clean up any unfinished task business by marking where you
// stopped or ending the task outright.
[application endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
}];
// Start the long-running task and return immediately.
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// Do the work associated with the task, preferably in chunks.
[application endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
});
}
我是一名 react-native 开发人员,很抱歉,这可能是个愚蠢的问题:)
我怎么知道我应该从哪里导入这个方法? applicationDidEnterBackground
Docs也不给我答案。
最佳答案
有两种方法:
AppDelegate
你应该在你的 AppDelegate.m
中实现这个方法
你可以通过查看 main.m
文件找到你的应用程序的委托(delegate),你会得到类似的东西
int main(int argc, char * argv[]) {
@autoreleasepool {
return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
}
}
AppDelegate
是您应用的委托(delegate)类。
NSNotificationCenter
有一个内置的 UIApplicationDidEnterBackgroundNotification
通知,它在 UIApplication.h
中声明,并且
您可以将任何类型的对象作为观察者添加到 NSNotificationCenter
。
[[NSNotificationCenter defaultCenter]
addObserver:{myObserver}
selector:@selector({myObserverMethod}:) // adding ":" at the end will provide you the sent notification as parameter to your method
name:UIApplicationDidEnterBackgroundNotification
object:nil];
现在你需要在你的{myObserver}
类中实现{myObserverMethod}:(NSNotification *)notification
// MyObserver.m
- (void)myObserverMethod:(NSNotification *)notification {
UIApplication *application = notification.object;
// Now you can call `[application beginBackgroundTask:]` or etc.
NSLog(@"applicationDidEnterBackground");
}
注意:不要忘记 prior to iOS 9你需要在完成后调用 [[NSNotificationCenter defaultCenter] removeObserver:{myObserver}]
!
关于ios - Objective-c:未声明的标识符 applicationDidEnterBackground,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42650830/