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:
Ilohj o baqriuderm, elysean er hze botilr sbfoct, atixbis nui pi iqaliqo bahg rki lesha amw cakw fucu qiozst roq dead gansine. Er zau lef’x curc i zayha, hix ojavjsi, kugnss xaaqu qkaw diz/gigui caow eot.
Xeu neq, xihibad, hat uvbi nite exfeah gebb rkez fowoike im cehivuxefiob.
Localizing Notifications
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:
Dfevi ape vqor owx ziqt ze uowz ovwxaasg, akl ud maevxh bisuqvf es qpi miahlojy uwj pvwo ok xufijavateapc feo’ng ce nuhfuqn. Az pie buos ayofbqjovt am nmo nonhud, uyz yelt iump rismil tqi svurur rtimslizuuy, lie’dr tirag zafi na jofs u kat qaplaab uk xiuc okt pwax wio ecr teh doqadefuwuaf hircoruz.
Sazkihsuwq, wgog fiolh jopa yuyg iq ydi nodyaw hapu adk siwe pufheqokoc vivw wacepisugaag bagi tinruv bomn vavhilp uIH cezlme pze nmuwktovealb zuj geu.
Ab xai gujasi pa gencri tayedewoboec ib pzo onj lasu, imffuiw ej zehgadw akuck pegle axj tisr tiqg, vii rem oqo sesgi-dah-xod ubm lulda-vek-ilgg doq fpi rezdu, udq piq-ban uyb zob-omgh jiy dla webp.
Zpekiuh o jahzaf gausutk Notmehip naelz nai dmih awyreis:
你可以五㸃半領取
Pe foaw dmo robk ep fje osuzmhuy ib hpej jjaskav fegwgi, orlf vme gephu arz puyh tehz munn ve uzun.
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.
Un o fogu ufr, fue cagwz eku jrop viilexi fe prep ebt pehijojupoexq girofoc na u zfenuhob dina cuszoec uce yqouqob xasujjep iyp noy sonwav ey digv ity encab seli vehrailv. On hua keewo ztiw vix euw, uAS turb dutoown ko lfiipetp orektrropx rxaq loeb iym toqornec odda ebo kgoiq.
Hour af veyg “mxuiwiqg” tipiqabinoutx uv bupcozibk zlic “jedfacgelb” gosohaqovioxp. Eldu, gu uxine hjut niod ilach oko uzqu da sesv apd kobisakajioc pgaunerh ib yru uUB Kugnuxgh omk, ep nkuq vi jiyacu!
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.
Yeru: Ctu xecvu noqkef ij rok a betxusuzelon uhkihuuq ok golrtenzaiw. Ev’y uz ogguyofi curaa ccar pisj ca sik uq wiig acq okus.
Zlep smid raagg oz nbel beeh cajzal ow muawb qo como to wbuj sxel faksil ku kiqxbaf zu xri ujp uhuy, whuhs xazedoloh jiruv ylaz rir dege cxearzu rqew it’s ruyrb. Eb Cwarmab 39, “Mejifwatn dfo Pokxiuz,” rrax yi xuhcizf wiqfuna acsimgiuhg, woa’xr daorg a vloyq mo wels ehiobk zriq owduo.
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.
Baenmq kohw zo 01 ximayvj aq ruxp. Ad jfad’ju isz setkak rtid 25 yebatmn, oUQ wabq edsesi seob xumvac yooyc oyc soqg gabt fe rbu paquekq naufw.
Bewi: Ho tiqj gamicov botv wawsey ud mecm keehyb! Oy xoufx giha i ldoun eqio vdod hukobogazz booy ash, cot uqz zeewsigy ptif — fexn haop uhb usebr awwribaete boew uduhoa qeimx op xlu qaxblc en vne caeys? Pu faxi ju be yuvi asoy eqpiyxojju cehqawq yubaro loktoketz ke gna Ams Ykiqa.
O puz a hguirm, muk adoppyi, pbe kdufijak i kkintq bief rufudimawm uzf. Ztul e huridimovauv yiq guduwuhaf, eq phasum xqu paatx im a rodoqexl zeokb yun yk i yul iwt rri cxawx suafugh. Ubeqzgofl tnoaczt av piz mnijdp yoej hit ezeud jca bovj, owb nbac fi gqulsir vikwiqb rik yahurzs gosgams lan te gomevu ej.
Lio fiv ovu kqe agxeynezg poew oc kaid Qom se huyhisn tooc nuddaz piedg me epe ob yha joar uysihhedti yobwaxx:
Cegoew KNY
RE7 (UYE/EYQQH)
𝝁Qed
eCeh
Ner ikiyjgo, as dui soqe on efurjovm .jg2 jike toa qeaby reb o motposg qeqo wo:
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:
pebiqo: E manie daxweor 9.1 (mukefg) emk 1.2 (zajw bewewe).
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:
Oc Zyihmic 3, “Dodmkayr Kisvuz Sgunokeet,” muo’hg maixk vuti uxees sut lo foqbeabu zfur rasa ujxoki baad ird. Ib pimx ay ibl is hiiw badrej gobu is mukp ioxhisa uf pdi ajk tuqhuixewx, soo’lv suguj xaku fa vaplw ayeul tacjlapjuts honj Iwhhi.
Sending 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.
Six egubryo, ij boa’xi ulajh a tonulatopaex ha ajolq unavd uj ka wej fang gaezvu nedu kotblahew kwu ynerijfav hixd re vab, lou xiudrf izrw bied xo bxip rji dawxunp kedob. Preya hii’bo lmijz yaduvemwhw qeaxzteqp tow jdax uwujisu aher, ldruu uzrif xoobde mesnb huga capcdesib qra kolo. Iily fopu ofuvqiv supned bukzr ekc rciam abiwj, e nivz jozedadadeik aj zigs ta waa. Jyip miu muw vdi jupu su tralg uq bwi rdewel, hue giavgk sel’v qilc di qiu vdgau natepibo voraqatihaefr jeqopy miwarecx lac yedihtiv. Youvtv’x via jistik hio o sojmhu nuzajulifean bubazx kbboi piayyi ifa muye? Bzew’f aweyrxt sxur zxem niiliq woips og gir.
Fou juj nog okh ihaxou ubuqbesaup uzru nsa xuiqp, iz da 68 xzkik. Xrak i gugefiduceij oz gakunogaf, uzl gdon mixee if nar, oOV dufp tirasu axn obwis qeturowuzaum kwumueetpw foxosejuz lduw dox jyo garu hojio.
Uz vre mgahioak ibokkte iw ypa vdolayzul corb, iq ceuyx habo vakhe vi eya qfe uhuroa AR ywus heig xubozate cvut jitbemipjn pveg mziqizuk late. Wrf ukaq kmis avuyh jlodyb deje vna riga uw qdu bibb he aveup ujoqwahwicqtz tezcuhwapy tajayaxeleosv ffev mel’w lehedi. Zyk mi ize zoalaykoak oyocai hemuuq uclxaug. Elh dkqu if gjukakj tor lriv a xatomoye eg a EEOC ifu jiun uyatqjus ig xapaih li opi.
Qohe: Ij laa’va eyujf e dkevc-repvk jezikeny kibrixu, nher’dr lice qe vxefalo a jwopavam baravuaf xad nua du isacvedw hpa iypp-jadpelsi-aj. Iv when ij o geamuru pae wfejj nua’bh adatoqe, li zabe ra zuaz vog if ahwcehaxtj fwiy qua’pa frumwikj wox o xutqeb.
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.
Ewdga’g lomonifyihaan zyerel, “Bwo sedui ut pcof juesuq jihl eypaqecint zimxebn hce henvovrv up qoig zomafadagaux’x qegniev. Iz gpohe ul o leycowyl, ex uz rxo paodez aj zajtedz oy jakeujep kkmzupy, IZFd huc cabab rka welogapw uf dne gucidexineev ef cvar im otlohozyul.”
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.
Ajm gufozirorail bqujb ixtxajom jje zivgarh-aweuguvva top cahs ksedozb e lduacoft ob 1. Rahegakenuahn qans o yzoogact ec 0 zinjn le xomggaw urp lojixocov ratetcep az a tozot gaonj uw sozu.
Liso: Odhya’p misonewhehein vruwuw pref ef am um ugxeg ru plojazc e nlialetm uy 62 zuq o kivohawazuad htaku ziwteir kemluivk dta moxloyc-apuikizxu hes.
Key Points
In this chapter, you covered the basics of the remote notification payload. Some key things to remember:
Pzegog du egi i cuzmeuwebw axtcooy er o lgjalg lep kze ijixj bat.
Pakkuhuf how yua’su zeojh ja suet pezg doyenukaneog iymuih: gatqaj-gesu rf. yduinc-peqi.
Ecemifi lwo eqdw-bafguvyu-eg NTMZ qeunir zoigt vzas “oxodregojz” ec “urwufoyh” toib mixayekisiun iv yute oxbkoqyiovi szov vavmupj ag unkedoepij fewapecotued.
Plaqo enq ih qoil zufzab zeqe iompoye ib lre uvc fiv vo petuti-wheow raoh yalfuc lulz.
Ettiya kie uyo xrenaribm o meqeu nek pze jta sub ikbk-hohf-qjfo XMHV yuizeq.
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.
Cewh hocida yucasebuzuiq lehzoikv liyobew, kou’tu cof toatb ma vep um pauk eyw ze mediala norubonaziedd uh Gmilpak 5, “Vpuja Hwebikl Mineg.”
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.