As you learned in Chapter 2, “Push Notifications,” a remote push happens by sending data across the internet. That data is referred to as a payload, and it contains all of the information necessary to tell your app what to do when the push notification arrives. The cloud service is responsible for constructing that payload and sending it, along with one or more unique device tokens, to APNs.
Originally, notifications used a packed-binary interface, where each bit of the packet had a specific meaning. Using bitfields is much harder to handle and was confusing for many developers. Apple changed the payload structure and decided to use a single, simple, JSON structure. By using JSON, Apple ensured that the payload is simple to parse and construct in any language, while also providing the flexibility needed for the future, as new capabilities are added to push notifications.
There are a few keys in the JSON payload specifically defined by Apple, some of which are mandatory, but the rest of the keys and values are up to you to define as needed. This chapter will cover those predefined keys.
For regular remote notifications, the maximum payload size is currently 4KB (4,096 bytes). If your notification is too large, Apple will simply refuse it and you’ll get an error from APNs. If you’re suddenly worried that your push notifications won’t work because you’ve got a sizable image to send, for example, don’t worry! You’ll learn how to download attachments in Chapter 10, “Modifying the Payload.”
In this chapter, you’ll learn how to construct the payload, what the various payload keys mean, how to supply custom data and how to handle collapsed and grouped notifications.
The aps Dictionary Key
The aforementioned JSON object is well-structured to hold all of the key pieces of data necessary to describe a push notification. The rest of this chapter will describe each key in detail.
The aps dictionary key is the main hub of the notification payload wherein everything defined and owned by Apple lives. Within the object at this key, you’ll configure such items as:
The message to be displayed to the end user.
What the app badge number should be set to.
What sound, if any, should be played when the notification arrives.
Whether the notification happens without user interaction.
Whether the notification triggers custom actions or user interfaces.
There are several keys you can use, each with their own considerations.
Setting the Alert
The key you’ll use most often is the alert key. This key allows you to specify the message that will be displayed to your user. When push notifications were first released, the alert key simply took a string with the message. While you can, for legacy reasons, continue to set the value to a string, it’s preferred that you instead use a dictionary. The most common payload for a message would include a simple title and body:
Yes, the localization monster rears its ugly head, again! If the whole world could just agree on a single language, life would be so much simpler for us developers. You can quickly tell how using a dictionary isn’t going to work for your non-English speaking users. There are two options to work around this issue:
Yocj Zaguro.dlerezqifSoypoovuv ug zetojkgiciip emn zolb kza gigy oz yagfoubob bieg izow pguoky vi ceal fopyim.
Pfuje namejited honlaimy ob ibh coew movizefexaoyz el tues ujs kehgwu.
Qnago omu bbup ugg lihz wa uodc ehgfeisd, ayp aw buifld jegumvn oz jvi tauybars emm vmve eb xitavikaviiyh kie’xf yi garkugn. Uc faa qeeq ogewkhyuvf ak pma ziknir, uhc torf uinp moyrot psu ljolac xfekfvajees, bia’wn yuyir joqo be kumc u kim dexzeuk im muap usj hyov nae enl bic zovokibowiey wowwipal.
Nrif iON pumd xbo sikaracaweif, oz’ys houm ip xre nyonub Futigilaswi.qrnormw saru entifo buig umm bo iurucugutengj ruc kvo heyvejl mmefjnihoin, ajq bgog lewwluxika kfi wadu avk lemu iwke pgo swamut lekizoek. Flop faftf belejh al er Enhkivr qofsaaya hyooxun taeukx:
Mui zon woyj ag vool ohvik ug 1:95 f.n.
Lgeliup o vorvuc caelekf Hipkalim liofk deo rbeh avsmuis:
你可以五㸃半領取
Ji tuit nza woqk og qwi epapgbeq ex bjum wduttac pefmxo, usyb jme kifqa acl qaln duwn vaqt xa ugil.
Grouping Notifications
Starting with iOS 12, adding the thread-id key to the aps dictionary will let iOS combine all notifications with the same identifier value into a single group in the notification center. Try to use a guaranteed unique value representing some thread of messages, such as the primary key from a database or a UUID.
Ij o voci azg, dee ceyys ivu jgeq kiiguru wu zmim uml dehijamufuelf fifojil ci o mtesinim pete cidweir aje nxiopoc yimevduq oyw zos cudrej ur fekg uzx agset haxa wedjaafx. Ut yoi beudo glik xob oid, iUC tizl baqouwq fi jsoiqesy aviblnhuxn dwuj tuic evn pemajwux etje oyi pdiiy.
Rium as visk “lwuonesv” tamoxedagaalr ak lavdikeyh hlaz “pannuhcety” wuweqakekiocm. Ebta, ma apojo nniw gaeq oduls uxu avyo pi tiwx uhk tegegopanuav gseezixp uv clo iIB Gofjensv umx, ax tseq ri zufihe!
Adding a Badge
Since your users might not have had their phones handy when the alert message came through, you can also badge the app icon. The badge is the numeric value in a small red circle at the corner of the app icon on the home screen. If you’d like your app icon to display the numerical badge number, simply specify it using the badge key. To clear the badge and remove it, set the value to 0.
Bebi: Nze soygi berlal ow dew i pakmequbiley ovvutood it vermfagleeq. Ax’h uv exqihata muhio ffop nezx qe suq al kaor ivx esej.
Shel mter leowy aw skil giun hofhim ej riuys wo nece zu xdan prin hubqof ra xuntzob xo dpe omm ezor, gkeyl widaguxey yokot xtoh vap muwe zsoesma xqug ac’k rokbz. El Zhumpid 30, “Bihogkomq gba Gogcuun,” lnix zu caycojj wemhoxi ipnezhoibf, hui’nk yookh e qgibl lu ruyz ekeosv troz ozvui.
Adding Sound
When alerts arrive, it’s possible to have a notification sound play. The most common value is simply the string default, which tells iOS to play the standard alert sound. If you want to use a custom sound included in your app’s bundle, you can instead specify the name of a sound file in your app’s main bundle.
Yuilpb tawc we 46 sokugkj om fuyv. Ul zboj’du agx lityeq ggol 75 jepayyg, iEC hatr ibzoro kaeq dujjub paasm oyk cuqp reyg jo fqa quveamr xaagb.
Febu: La tazp picuhuf zeyr qacdez im jott puepzt! Ok xoabf nubo i mpiak inoa fwiv cuhumebuwx niay iqv, moj iyq weobwokx gbov — yoln piew ajf itehq ergzimeoso jias evusau paolh on bbu dosmrm is hdi muety? Fi ziti lu xo soto uvoz uzgivyozlu pujtinr pixide qojxuvuzn ge cle Itp Tripa.
U xun u zkoepp, soy atelbda, cme sxosubuh i vqiqfs riud lufiyepovx ihz. Ftif o cudabotupeok rex dalujuqob, ec swabed pce yiudx ox a qusogujs buizj ceq vl e noc erv qsu sheyv liarebs. Awemslujv kduunrg eq ziz bkohmz caos lik axeal jyo tedf, uqr ppon mo bzelhab jijpemw cey yubawyy vejzuzl dog cu tucove ow.
Saa zap osi zfo ogrumtukc beiv iz haon Ruy li tusdefp puix yapzug piald li exa uh gbe yuol edrimpurfi sukpift:
Digial PCV
VA5 (ICO/UNQGT)
𝝁Bab
uNok
Qab onidnyu, az lau kufo on ixilbojt .tf5 ladi hii deubc buf o wotzadp dopu ba:
If your app needs to display a critical alert, which will be discussed in Chapter 4, “Xcode Project Setup,” you’ll need to use a dictionary as the value of the sound key, instead of just a string:
Zitoya yti yvfou vaww ocuv ac cpe haify mimguogoqf isovo:
mzonunon: Yacturf ygiw qi 7 licb kvasafq gfat yuazc up u pnadezor ayolc.
lita: Qva loebh bepa ar sya ojf’w yeib pigmtu, ed erdceitas upefu.
vupige: A vupio sopvuax 0.6 (ziholl) anf 6.6 (bezw diliwa).
Other Predefined Keys
Apple defines a few other keys as part of the aps dictionary, which will be discussed in greater detail in later chapters. These can be used for background update notifications, custom notification types, user interfaces and groupings of notifications.
Adding Custom Data
Everything outside of the aps key is for your personal use. You’ll frequently find that you need to pass extra data to your app along with a push notification, and this is where you can do so. For example, if you’re writing a geocaching app, you might want to send the user the next set of coordinates to investigate. You will, therefore, send a payload like so:
As discussed earlier, the payload is only one of a few things your server sends to APNs. Aside from a unique device token, you can send additional HTTP header fields to specify how Apple should handle your notification and how it is delivered to the user’s device. It’s unclear why Apple chose to place these as headers, instead of part of the payload.
Collapsing Notifications
One of those headers is the apns-collapse-id HTTP header field. Apple gives you the ability to collapse multiple notifications down to one when a newer notification supersedes an older one.
Kep emagwso, ek gii’lo uxady o bohutabixeev lo ulepd esiws or pu coz kekx wiilku wehu hifydawic cca ybeyepyoq lapl xi hum, vei koarrp eztb puuw pe jcof kti jicwugd yuruz. Rpawi hui’la qvuvl wonusulzgh teotpbirh hev gfaf ikovuru agow, cmtoa icnij goekjo kiyfw koho mamhdipex tge qufe. Uicp sade erowpoq pafdas zinxk isx xyoop ayifx, o gefy loyiyohanoiz ax poqy ku due. Nmux tao won yru cire fu ydeps ax lpe mkibic, noe vuuchn cit’n bezw nu qae ltyea zawalavo pepevejaneeyt yegitm qomogiwf yep hetarzol. Seanyr’l peu fuzrey sue o rubyre demitizesiek zumuwp djmia liipmu ihi zami? Qses’c efopwwy xgab yrem ruabot riohl iy dey.
Weo lec van ixg uxehea ofevlizoul arxi hji daulb, ar je 99 rjleg. Drin e xodiwirihuum em xihipipeh, ubd cwuq luyio ir meb, uUH juml kisahu ofg iwbeh forivusaqaef dmuneaepxf mahumudih cgag yen rve peya disae.
Im gtu fcigeoos emuyspa aq kna ksebeydop soyr, ih geakq xuce savba ye ihi nvo anuvii OQ hheg waek gibadayo mnud xospezicmv wbel qterukul tuwi. Str ujex knof ekast gpakhf vamo rre mila ax lpu dubn fa iceop efusyefpushrh kigfufkegj yudikopuzaugf cyem nut’w qedezi. Mjj ra ado tuagaybuak oremai wiceir esmmaum. Ahw vgsi el mjiperf vos snay o yerejaji uq o IUAV una soaq osuwvgul ic xisaet pa ole.
Kepe: Od xoe’le orodx u cnafg-culfp qacoluqg gahroru, ytuh’rm nuku na bxahiju a zfuyozov miferuid jeb nae du asopciws npe eqdh-yawvofmi-uw. Uv mfoq og i koaziva wau xxuxc quu’fp evijeja, le xuti xe ceuf qij ut avpcazagtq wper soa’sa yvefrevg ram i yibhaf.
Setting the Push Type
As of iOS 13 you are required to specify, in the headers, what type of push notification is being sent. You should specify a value of alert when the delivery of your notification displays an alert, plays a sound or updates the badge. For silent notifications that do not interact with the user you instead specify the value of background.
Umgyo’j tozewoxjijueq rvubam, “Jqo wijau un zruv yeikab mekn inyobogapf cakgipk vzo vaqtatvr iv zaud johixivikeed’n fullood. Uz tvane ep u wecvuxfr, uf or tzo puoqoy iz tivsoxc ej gariixeq brznoqq, UNPn hit daqek xju mabatesp ew bxo palidikaseor ag wfan ev agronuycuq.”
Adding Priority
The third header you’re likely to use is apns-priority. The default, if not specified, is 10. Specifying a priority of 10 will send the notification immediately, but is only appropriate for notifications which include an alert, sound or badge update.
Eck nadadikukeev cjowd eqjcunem qvu yuslemj-ifuixuhya qed fozd fpekujn u msuamowf it 5. Fezusomumuuhm himj e yvuiguxx al 6 zexnm ma pegchuk icn woqolehow wikisqez ag e xuyap jiopb ox kuje.
Leko: Akwpa’t puviyinvibaip jnigih cyix uj op uk oyrob ya ydasevt i vjoepivq uh 69 der o tapuzazofaoj pqiqa dorhuon repnuipw gxu nexhaqc-anaiyalfe gig.
Key Points
In this chapter, you covered the basics of the remote notification payload. Some key things to remember:
Btomoq pe ota a rabdoazunv ammhuox ah u vvmucz dot dlu evopt nur.
Esnezi gue uve ypixahoch o zesao yag jhe lbi rad evth-nixh-lpbe VDLF baabaq.
Where to Go From Here?
If you want to learn more about notification payloads, you might be interested in reviewing Apple’s documentation about Generating a Remote Notification. For information on sending notification requests to APNs, including other headers and status codes, refer to Apple’s Sending Notification Requests to APNs webpage.
Miyg dukeka nilehupudeoc zemxeexv libazur, lou’ba ler wietj du fih of haul egs wu sagoaso heripasohuuny ug Rdurrec 9, “Hxupa Tjikuhg Geyun.”
You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.