您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS App Extension 通訊:在 Host App 與擴充套件之間互送通知

編輯:iOS 開發綜合

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 與 Extension 都能編譯進去的共用檔案裡,避免兩邊字串打錯導致永遠收不到。
  • 回呼是 C 函式。它拿不到 Objective-C 的 self 語意,若要在回呼裡操作 UI,記得透過 observer 指標轉回物件,並確保所有 UI 更新都切回主執行緒。
  • 一定要移除觀察者。Darwin 通知中心不會因為物件釋放而自動幫你取消註冊,忘記移除可能導致野指標崩潰。
  • 它只負責「通知」,不負責「傳資料」。Darwin 通知的 userInfo 是 C 結構的 CFDictionary,不適合塞複雜物件。要傳遞實質內容(例如剛下載好的皮膚檔案),請搭配 App Group 建立的共用容器,Extension 收到通知後再去共用目錄讀取。
  • 兩邊都得是「已執行」狀態。Darwin 通知沒有暫存機制,如果 Extension 進程尚未被系統喚醒,通知就直接消失了。需要可靠投遞時,App Group 的共用檔案或 UserDefaults 才是比較穩定的選擇。

以上就是 Host App 與 App Extension 之間互送通知的做法。總結一句:Darwin 通知解決「即時告知」,App Group 解決「資料共享」,兩者搭配才能完成完整的跨進程溝通。

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