---
title: iOS NotificationCenter
tags: iOS, NotificationCenter
description: iOS NotificationCenter
---
# iOS NotificationCenter
---
## 情境:
- 因設計了帳密自動登入造成APP版本更新時,無法正常跳出更新提示
## 解法:
- 運用iOS或Android的訊息廣播通知ViewController或是Activity做對應的動作
## 實作方法
###
- Step 1. 註冊為觀察者
```typescript=
// 註冊為觀察者
NotificationCenter.default.addObserver(觀察者, selector: #selector(觀察者用來處理通知的方法), name: 通知的名稱, object: 要觀察的對象物件)
// 下面這段是範例code
NotificationCenter.default.addObserver(
self,
selector: #selector(Login.updateDone),
name: NSNotification.Name(rawValue: "updateDone"),
object: nil
)
```
- Step2. 發送廣播訊息
```typescript=
// 發送廣播訊息
NotificationCenter.default.post(name: 通知的名稱, object: 送出通知的物件, userInfo: 要包含在通知裡的資訊)
// 下面這段是範例code
NotificationCenter.default.post(NSNotification(name: NSNotification.Name(rawValue: "updateDone"), object: nil) as Notification)
```
- Step 3. 收到廣播後做對應的動作
```typescript=
@objc func 觀察者用來處理通知的方法()
{
// do Your Job
}
// 下面這段是範例code
@objc func updateDone()
{
// do Your Job
}
```
- Step 4. 如果之後不會再使用,記得ViewController或Activity要刪掉綁定廣播事件
```typescript=
deinit
{
NotificationCenter.default.removeObserver(
self,
name: 通知的名稱,
object: nil)
}
// 下面這段是範例code
deinit
{
NotificationCenter.default.removeObserver(
self,
name: NSNotification.Name(rawValue: "updateDone"),
object: nil)
}
```
## 參考資料
- iOS, https://www.appcoda.com.tw/notificationcenter/
- Android, http://www.aaronlife.com/v1/teaching/android_broadcast.html