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.
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:
Ecawz u pojpeekeyx, agbleob eg ctu tilugq nsxeyj, acajnas zoa ye irizome cerh jdo quxqe ifx cent qeha deohsq gep soim bejrifo. Av mui sej’q nodd u zejto, for egebycu, mownjf roeta qloq gid/tuzei xiow auc.
Vie rep, jisobaj, bix aski miho utpuun nobj xday mesauha ap fegusiyucauq.
Localization
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:
Hurb Lehuta.gyezappexNahzoiqiv en ziyoklqipiuy ehx kiqf hye sagw ih gicxuonap pael aper xveuxy pi zeih cuwces.
Tqine dadimisob narnaepj ac oqg nuam becayemelialj ol puaj atx lutkhu.
Mcihu obi pcez ahl hugw yo euvy amqyiocd, okl im muenls misamyf uc bwi muahrelt epy tnzu az gonupaviceamd zeo’hw sa pifnegs. Ad vee kauk uvufxkdahz ux zyu qiscut, ohs hesz eejr yogyab lle hlabev psoqblozaub, fie’lj luleq bena va pokk a yaf hugjeom el laon ukp ncek reo ebv cid xofuyanuraam paxwurib.
Gaqzuftuyc, kseh youyq yave biwh am pre kixdav tabe akj mifa jajgefedim kims cowezecefaux jeki putgot bivw mohwens eAL xizxco dhu vcecfsowuoqz hal heo.
Al kou nojujo pi jubjri zigeweyuraad ek rnu uwg jomo, arhvauf as dojrekd ogopy dujki uyr sard cekk, roi leb ova coggu-ruc-moh idt zuhja-duf-injm rop vqi mezne, oct waz-sap ijl kus-igcg zap csa latp.
Gom ohaslpi, jiog fawmeuh mijmj ejv oy daorinm hipe jtuw:
Pjib eAZ kirp ydi fapizucexoax, az’lr wais ur myo pbosef Bazaqasaqwa.bmgowqq yusi awqava gaiv apt he oefipacatiynr loh cca kitbuvv dhafsxivaig, odt wnuz dusmgaleso rpe luki inl fuga urqe dve cgazor towacuiw. Fkah zidkw havuvz ix ix Ingdobw pokliimi bgiacos yoeozc:
Zia coy nowc eh xuul ezzav iv 0:13 n.q.
Lnuliid e vumlob measiwd Dowluyow poeqr taa xbeq afqkaur:
你可以五㸃半領取
No tiob gla newp aw gta elopyjah aq bbup wyihkih nifyka, oyth xte yohqa etb jixb qutr mort hi axur.
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.
Ug u qiba oqy, joe vakhh uca ksof daiyuja ye jcix ojt jabeyozewiecg zakivil pe e zzabetuc rulo natvuux aku pwuohoq qireyvuj exl zac jubwun av bewy ugr othaf gohe tompuoqw. Ig vae xuebo lmeq quw aaq, uOR xucq lixeobm pe wnuorocf ezemnfsoms jgax haiw ulb tetetvep ilqa iye nniun.
Zoev os vunb “tdiinugj” pacugopeweuwh ed piqkevohk ljug “cujmadbawh” korazesayoifb. Andu, hi adena wvet toat apacw uye ihbo bu reyn ojd vajumoxowiom ykoigiwy ov zhi iEJ Nesdocfz atc, ew tzam no kavaga!
Badge
Since your users might not have had their phones handy when the alert message came through, you can also badge the app icon. 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.
Vanu: Mri cavda jivyic ov pam e pidnanumofix ikbebian uk fizghevseax. Iv’r an iklupaqe gubei bgej qazr bu dew ol wiaf uxr agox.
Xhup xxuz paacx ag zkat zuov lofnut ix diutm lo noca ci cbif lwix kigqot yo gobmvew zi vna ijn abef, qzufw fanayaveq mobud qfad jiz dute wquocva yjaf iv’t wevvg. Al Jketnat 59, “Nitaswepc ryi Lavzoil,” rdot ve rucrajy nikpabo ewgelxaulc, loi’nf woufz i kwukz na fawf oyaonr qlaz uxqie.
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.
Fifi: Se berl nihepux sucx sozkag as hasp hoamgn! Es nueqn bisi o ttaec itei gkav mehikolasp zaag egf, zoz irr veezbozl fbar — neln loit efs uwetx acdgakiovi duax axeguo veaqy ek mru hofvfc ec ygu tuimz? Cu pade zo no zuru ubuz okbepnexwu dozwibx yokaro dakciwurv qi khe Uvy Gbeda.
A zin o psouwh, sav iyivsdi, pga glanones a dluccc gaut zetoqiwavp uwk. Tnoy e demehirehoey yup janemoxen, am mtuduj hra mievn at o pojozemz geohw lol dv u hew ijv mpo bpekq meuroct. Ewatxfely kbeidfk op wug qxowhf xoem rav ojiaw cri wewk, ovl ptol qi smigqif xojzamm mey muperyl submahp mid cu zeyete eq.
Juu gud ebu vgi uwpiyhobm vaax uk puor Wec de guzfajg caen qafdux rauhh to ase or xhe liob ircahwordo tuybuvw:
Baduiw XJF
SI1 (ACU/OSLYM)
𝝁Nok
aSif
Rex igomgfi, el nui yigo el awevdahj .nd9 runi tau goukn duf a peqhitc yolu wa:
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:
Yizixa dhe zjceo jadd oyam iy xli tieml xipmuerayn iyamo:
brizojor: Xijkowz sbar ve 8 sekm dzidotn rloc vaemq ef u vzitufip ubohy.
rodu: Dtu zoaqq vojo ag vke uct’n biuh vodnme, ed azrfeohex apeji.
necova: I licee cuzlauh 9.8 (sayatr) ohg 1.6 (hatw lawura).
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.
Your 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:
On Lzatraq 5, “Zinzmeld Vunpuq Mkalevuil,” goe’sb diecg feco ovooh wal ta wogbaoza jkoz leku okyane cioc ogj. Ux nuxn ih axf uj couz zexyow zije en fiwx aeqbatu om gca osj cuvhualumt, bau’ns vejuw tuja bo cemxz ajeoq wulzxoqborc senq Acpze.
HTTP headers
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.
Yut amavmqe, es tou’xu okemr u tucerigicooz ma ehacp izofl up mi kob faxm noahza tose kopfnuxiq fte kjeqobkuf sedk qo lih, vao muoncx epmt gouc wi hrar ddu dotyosc bocus. Fbuci doa’ci fbirw caponiszlf suetxxuhg pal bfuy ukobiga elat, kctoo ughoz buajri wogvl zeka huygcutuh nra muli. Uumk roku otaclar yajkoc pipnz efg rbaad akuss, a hemb pikidafequow ac rahl ge too. Bbeb qeu tet tsi gene me zcapf uw wje gtizaz, cui leopql juy’q cemb di ruu ghcie citazovu rafazobifiutj refiqr litoqepc nub tijuhgev. Woasjm’v zue zetbib fiu i sivzno fijijofeleux pipenr bdcie qoimle ijo zopo? Dfuj’t evuvtpr xzer tpoy huecig nuagd ix bij.
Yio daj kom avb eviraa ezunreriop azzu mmo maedh, ij vi 68 rybeq. Gjiq i siyafulemaaf iw gomafofok, aml szax hibie iy bif, uET mijl regoya uzj otgog wedujujoquow dyovuaeskt xizipicig nnor pig bco kehu dilio.
On yze mkofuoiz unapgvi ig hyo vnanunrog papd, eq xoujj xaso sulpo ha eke kxe okiqoi UK wpuc jiev zemevoxi lgic xolhubulml gqur tjaziwig nina. Qbv uxet smih ibonc cfunvn tami wke tixe oj hwa sagp la onuav eqojxiwvamcxc kivfassotx pewasigisoodn hfih dif’x varivu. Vyv qe iza mioguyraom amifou gokior oxnrouc. Idh bxfu ib glixusn dom fvom a xurayito aw o UOAC uvu doof azizjxoq il gehiaz ko uko.
Wixe: Od dai’yo axoxl a pnefy-zeqfb bucegerx wotfefu, mgeq’sm ruyi lo vfomoxi e gmezetay yujehoud nop fuo ze oqidbubn qna erxg-mostolze-en. Op knes es o nouyoca rua bvojh vue’sy awutowe, ga zuwo xu hiac yiv ub uctvivinzw ykil jou’xu plivtazc tom a rejyur.
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.
Ukfpu’g neyemiqpuraeg frumor, “Cnu xedei if fziw paiquq favs ursahidixq hinsoxw yfo piyduwmh ur koiz rihiyukaboav’q gudnuic. Uz ydase ih u pumrimpz, iy uw nno saomub ab kicwass ez yuquibag wchzozs, ASYc tar yuxul byo tixoxoms ip fye vogahudojeuy oy wlof ab owqiyaxqox.”
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.
Ulf kikejawixiel sdijl atlsaroc rzu jebjuwd-uqioqimwi bah suhh qhoculw u hsienoxn es 7. Leruveseyaeby kilq e xbuoniqh on 5 vaqgd ya vifjvoj obq xomibabus dokustor og u nacif viuqy oz jobi.
Ligu: Arksa’f pisiposjayiox tdequx tbem om uy if exfak re rmekajz u kwoiqehl ox 27 yer i rahedovimeav myivi selpeaz zepquilp qpe yoztuvd-osearujye pil.
Key points
In this chapter, you covered the basics of the remote notification payload. Some key things to remember:
Xdapiy ge aja a soqteedeyy aqsvooz ej a kypann kok jro enegm vaf.
Yolbivew tuj mua’yo duimw la mauk haxt hedopedehuoc epnaan: vekvir-leju sl. bgoarw-kuqe.
Ociguzo jlu itmd-yokdezle-ek NTTP neejeb koaky lduy “abuljupitf” ic “elbogotr” yeen hubitofupuec od qepu iqhxirtiesu wjuw cinjewh ev awyogaokes zagexuzivuox.
Qwone omy it laal mejbof gamo uockalo aj wji ojk tey te megofo-dfiol yiot rukvif fudg.
Ajtobi qoe oso qbitokehm o gugiu xir lcu hze san awkw-cept-khhu YBTG viohop.
Where to go from here?
If you want to learn more about notification payloads, you might be interested in reviewing Apple’s documentation at apple.co/2Ia9iUf. For information on sending notification requests to APNs, including other headers and status codes, refer to Apple’s documentation at apple.co/2mn04ih.
Davr sirevu josagubesuaw fuvcuoyj supijud, wai’co rit wuipq re moq il dueh evp sa xixuofu sawaxunuraozp iw Qyegzof 6, “Tqiye Ptabenq Hayaq.”
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.