您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 教學 >> iOS 相關教學

iOS 實現 Host App 與 App Extension 之間的跨進程通知

編輯:iOS 相關教學

怎樣讓一個 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 字符串)在發送端與接收端必須完全一致,否則收不到。
  • 記得在合適的時機調用移除觀察者的方法,避免懸空指針。
  • Darwin 通知不保證投遞時序,也不適合傳遞大塊數據;如需交換數據,建議搭配 App Group 的共享容器(NSUserDefaults 或共享文件)。
  • App 與 Extension 需要處於同一開發者賬號下,並配置相同的 App Group 才方便共享上下文。

以上就是 iOS 在 Host App 與 App Extension 之間發送通知的簡要介紹,希望對大家有所幫助。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved