總所周知,蘋果在iOS7.0后在后臺任務上增加了如下新特性:
后臺獲取(Background Fetch)
推送喚醒(靜默推送,Silent Remote Notifications)
后臺傳輸(Background Transfer Service)
由于最近項目需求上的變更,需要應用在退至后臺時在某一個時間點喚醒設備更新一下UI,在用戶下次點擊應用圖標進入應用的時候就能看到已經更新好的UI了。所以,研究了一下靜默推送,下面我給小伙伴們一一呈現我所實現的整個過程。
首先,在官方文檔中找到下面一段關于靜默推送的描述:
Configuring a Silent Notification
The aps dictionary can also contain the content-available property. The content-available property with a value of 1 lets the remote notification act as a silent notification. When a silent notification arrives, iOS wakes up your app in the background so that you can get new data from your server or do background information processing. Users aren’t told about the new or changed information that results from a silent notification, but they can find out about it the next time they open your app.
For a silent notification, take care to ensure there is no alert, sound, or badge payload in the aps dictionary. If you don’t follow this guidance, the incorrectly-configured notification might be throttled and not delivered to the app in the background, and instead of being silent is displayed to the user.
說的很明白,要想實現靜默推送,首先要在aps這個字典里增加content-available這個屬性,并且這個屬性的值要設置成1。之前在網上也查了一些資料,都千篇一律的貼著下面這張圖:
可是,參照這張圖的意思是,alert里面也是可以有內容的,可是事實上官方文檔里的第二段話被好多人忽略了:take care to ensure there is no alert, sound, or badge payload in the aps dictionary。好吧,看來alert里面必須為空才行。本人親測,alert里面有內容的話就是普通推送,是不能在當應用在后臺掛起時喚醒應用的。OK,alert字段確認了,是必須為空的,那么sound呢?由于項目的推送SDK用的是個推,本人跟個推的技術支持交流了一下讓服務端在設置sound的時候設成空串:
結果,靜默推送雖然收到了,但是它是有聲音的靜默推送,后來個推的技術支持更正了傳入的字段:
好了,靜默推送收到了,整個世界也都清凈了。
OK,到這兒,我們可以基本確認靜默推送在后臺的格式:(a) 增加content-available字段,并設成1 (b) alert字段必須為空,否則收到的就不是靜默推送 (c)sound字段設不設不影響靜默推送的接收,只不過會出現符不符合需求的問題。對了,還有一個badge屬性,設置的話也不影響靜默推送的接收,但是和sound一樣,看需求是怎樣的了。
最后,服務端關于靜默推送就設置成了這樣:
而前端收到靜默推送時的log是這樣的:
最后,總結一下,靜默推送只能在應用在前臺和應用在后臺掛起時收到,也就是說,如果應用未啟動或進程被殺掉,靜默推送是喚醒不了設備的。應用在后臺掛起時,收到靜默通知時在appdelegate里實現-application:didReceiveRemoteNotification:fetchCompletionHandle:這個方法,在這個方法里執行想要在系統被喚醒時想做的比如更新UI,請求網絡等想做的事。當應用在前臺時,網上查資料說還是在這個方法里執行,可是我打斷點卻不走這個方法,不知道是不是我們的SDK用的是個推的原因,反而會走個推的接收payload的那個方法。
最后,提醒一下小伙伴們,實現靜默推送別忘了Xcode這邊還要勾選remote notifications選項:
在簡書的處女作就是這篇了,感謝小伙伴們捧場,荊軻刺秦王!