App Extension 與它的宿主 App 是兩個獨立進程,彼此有各自的沙盒與記憶體空間,一般的 NSNotificationCenter 完全無法跨過這條界線。
舉個實際例子:搜狗輸入法的「更換皮膚」是宿主 App 的功能,而鍵盤本身是 Extension。使用者下載完皮膚後,鍵盤必須立刻收到消息才能更新顯示——這就是典型的跨進程通知需求。
解法是使用 Darwin 層的通知中心:CFNotificationCenterGetDarwinNotifyCenter()。它走的是系統級的跨進程通道,只要雙方使用同一個通知名稱,就能互相送達。
- (void)postNotificaiton {
CFNotificationCenterRef notification = CFNotificationCenterGetDarwinNotifyCenter();
// 最後一個參數 TRUE 代表「沒有任何觀察者也立刻送出」
CFNotificationCenterPostNotification(notification,
CFSTR("<notificaiton name>"),
NULL,
NULL,
YES);
}
- (void)receiveNotification {
CFNotificationCenterRef notification = CFNotificationCenterGetDarwinNotifyCenter();
CFNotificationCenterAddObserver(notification,
(__bridge const void *)(self),
observerMethod,
CFSTR("<notificaiton name>"),
NULL,
CFNotificationSuspensionBehaviorDeliverImmediately);
}
// 注意:這是純 C 函式,不是 Objective-C 方法
void observerMethod(CFNotificationCenterRef center,
void *observer,
CFStringRef name,
const void *object,
CFDictionaryRef userInfo) {
// 在這裡處理收到的通知
}
- (void)removeNotification {
CFNotificationCenterRef notification = CFNotificationCenterGetDarwinNotifyCenter();
CFNotificationCenterRemoveObserver(notification,
(__bridge const void *)(self),
CFSTR("<notificaiton name>"),
NULL);
}
以上就是 Host App 與 App Extension 之間互送通知的做法。總結一句:Darwin 通知解決「即時告知」,App Group 解決「資料共享」,兩者搭配才能完成完整的跨進程溝通。