C API 在 iphone 应用程序将进入后台时注册回调

C API to register a callback when iphone app will go to background

我有一个小型 C 库,需要在应用程序进入后台时进行一些清理。我怎样才能在 C/C++ 中做到这一点。在 Objective-C 和 swift 中似乎有注册回调的方法。

iOS13 或更高版本

UIScene.willDeactivateNotification

iOS12 或更早的

UIApplication.willResignActiveNotification

[1]

[2]https://developer.apple.com/documentation/uikit/uiapplicationdelegate/1622997-applicationdidenterbackground

基于此处的 CFNotificationCenter 示例

#include <CoreFoundation/CoreFoundation.h>
#include <UIKit/UIApplication.h>

void uiApplicationWillResignNotificationCallback (CFNotificationCenterRef center,
                           void * observer,
                           CFStringRef name,
                           const void * object,
                           CFDictionaryRef userInfo) {
    CFShow(CFSTR("Received uiApplicationWillResignNotification"));
}

void exampleHandling() {
    CFNotificationCenterRef center = CFNotificationCenterGetLocalCenter();
    // add an observer
    CFNotificationCenterAddObserver(center, NULL, uiApplicationWillResignNotificationCallback,
                                    (__bridge CFStringRef)UIApplicationWillResignActiveNotification, NULL,
                                    CFNotificationSuspensionBehaviorDeliverImmediately);
    
    //remove observer
    CFNotificationCenterRemoveObserver(center, uiApplicationWillResignNotificationCallback, (__bridge CFStringRef)UIApplicationWillResignActiveNotification, NULL);
}