ios - Objective-c:未声明的标识符 applicationDidEnterBackground

标签 ios objective-c xcode

我正在尝试使用来自 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/

相关文章:

iphone - 如何在单行中管理多个标签但没有。表格 View 中的单元格取决于 iPhone SDK 中的数组。

iphone - 我如何在 UITableView 上添加 UIActivityIndi​​cator

ios - Xcode 10 无法构建项目,因为找不到 pod

ios - 在 iOS 上访问通话记录

ios 撤消管理器 - 重置为第一个撤消

ios - 如何在 Xcode 中隐藏代码文档/注释?

objective-c - .m 中的接口(interface) var 和实现 var 有什么区别

objective-c - UIImageView 上的透明度渐变

ios - 自动布局并排内容

ios - 远程隐藏按钮