iOS 消息推送包括遠(yuǎn)程推送通知(Remote Notification)和本地推送通知(Local Notification),推送通知的形式從頂部顯示,屏幕中間顯示,鎖屏通知,更新App未讀消息數(shù)字.
遠(yuǎn)程通知
iOS 遠(yuǎn)程推送通知需要在App中開(kāi)啟推送通知選項(xiàng),申請(qǐng)推送證書(shū),實(shí)際推送過(guò)程如下圖:

App打開(kāi)推送開(kāi)關(guān),用戶(hù)要確認(rèn)TA希望獲得該App的推送消息.
① iPhone 與 蘋(píng)果服務(wù)器建立長(zhǎng)連接.
② APNS 遠(yuǎn)程推送推送服務(wù)返回deviceToken.
③ 客戶(hù)端App 將DeviceToken 與 用戶(hù)ID上傳至服務(wù)端.
④ 服務(wù)端根據(jù)推送消息系統(tǒng),將對(duì)應(yīng)的消息,按照devicetoken發(fā)送至APNS.
⑤ APNS 將消息推送至客戶(hù)端.
本地通知
本地消息一般比較少見(jiàn),加入正在做一個(gè)To-do的工具類(lèi)應(yīng)用,對(duì)于用戶(hù)加入的每一個(gè)事項(xiàng),都會(huì)有一個(gè)完成的時(shí)間點(diǎn),用戶(hù)可以要求這個(gè)To-do應(yīng)用在事項(xiàng)過(guò)期之前的某一個(gè)時(shí)間點(diǎn)提醒一下TA。為了達(dá)到這一目的,App就可以調(diào)度一個(gè)本地通知,在時(shí)間點(diǎn)到了之后發(fā)出一個(gè)Alert消息或者其他提示.
本地通知比較好模擬,iOS 10 中通知有所改變,AppDelegate中注冊(cè)通知:
<pre><code>` func registerLocalNotification() {
let center:UNUserNotificationCenter = UNUserNotificationCenter.current()
center.delegate = self
center.requestAuthorization(options: [.alert,.sound]) { (granted, error) in
if granted {
print("注冊(cè)成功")
center.getNotificationSettings(completionHandler: { (settings) in
print("通知設(shè)置---\(settings)")
})
} else {
print("注冊(cè)失敗")
}
}
}`</code></pre>
實(shí)現(xiàn)UNUserNotificationCenterDelegate:
<pre><code>` func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
print("didReceive 接受通知")
}
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
print("iOS10 通知")
completionHandler( [.alert,.sound,.badge])
}
`</code></pre>
發(fā)送通知:
<pre><code>` let content:UNMutableNotificationContent = UNMutableNotificationContent()
content.body = "Body:你現(xiàn)在學(xué)習(xí)成績(jī)不錯(cuò),繼續(xù)加油哦"
content.title = "Title:溫馨提示"
content.subtitle = "Subtitle:FlyElephant"
content.sound = UNNotificationSound.default()
content.categoryIdentifier = requestIdentifier
if let path = Bundle.main.path(forResource: "test", ofType: "jpg") {
let url = URL(fileURLWithPath: path)
do {
let attachment = try UNNotificationAttachment(identifier: "testImage", url: url, options: nil)
content.attachments = [attachment]
} catch {
print("文件不存在.")
}
}
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 3, repeats: false)
let request = UNNotificationRequest(identifier: "FlyElephant-Trrigger", content: content, trigger: trigger) // 請(qǐng)求通知
let center = UNUserNotificationCenter.current()
center.add(request) { (error : Error?) in
if let theError = error {
print("通知--\(theError)")
}
print("通知成功")
}`</code></pre>
取消通知:
<pre><code>let center = UNUserNotificationCenter.current() center.removePendingNotificationRequests(withIdentifiers: [requestIdentifier])</code></pre>
測(cè)試效果:
