怎樣讓一個 App 把通知發給另一個 App?典型的例子是搜狗輸入法:鍵盤屬於 Extension,皮膚下載完成這件事發生在宿主 App 裡,鍵盤需要第一時間知道。
如果你正在為自己的 App 添加 App Extension,並且希望宿主 App 能通知到擴展(或反向通知),下面這套基於 Darwin Notification Center 的做法應該能幫上忙。
普通的 NSNotificationCenter 只在單一進程內有效,而 App 與 Extension 是兩個獨立進程,因此必須改用 Darwin 通知中心(CFNotificationCenterGetDarwinNotifyCenter()),它能跨進程投遞。
// 發送通知
- (void)postNotificaiton {
CFNotificationCenterRef notification = CFNotificationCenterGetDarwinNotifyCenter();
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);
}
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);
}
CFSTR 字符串)在發送端與接收端必須完全一致,否則收不到。以上就是 iOS 在 Host App 與 App Extension 之間發送通知的簡要介紹,希望對大家有所幫助。