In the past few chapters, you learned about quite a few practical applications of the Combine integration in Foundation types. You learned how to use URLSession‘s data task publisher to make network calls, you saw how to observe KVO-compatible objects with Combine and more.
In this chapter, you will combine your solid knowledge about operators with some of the Foundation integrations you just discovered and will work through a series of tasks like in the previous “In Practice” chapter. This time around, you will work on building a Hacker News API client.
“Hacker News,” whose API you are going to be using in this chapter, is a social news website focused on computers and entrepreneurship. If you haven‘t already, you can check them out at: https://news.ycombinator.com.
In this chapter, you will work in an Xcode playground focusing only on the API client itself.
In Chapter 15, “In Practice: Combine & SwiftUI,” you will take the completed API and use it to build a real Hacker News reader app by plugging the network layer into a SwiftUI-based user interface. Along the way, you will learn the basics of SwiftUI and how to make your Combine code work with the new declarative Apple framework for building amazing, reactive app UIs.
Without further ado, let‘s get started!
Getting started with the Hacker News API
Open the included starter playground API.playground in projects/starter and peek inside. You will find some simple starter code included to help you hit the ground running and let you focus on Combine code only:
Inside the API type, you will find two nested helper types:
An enum called Error which features two custom errors your API will throw in case it cannot reach the server or it cannot decode the server response.
A second enum called EndPoint which contains the URLs of the two API endpoints your type is going to be connecting to.
Further down, you will find the maxStories property. You will use this to limit how many of the latest stories your API client will fetch, to help reduce the load on the Hacker News server, and a decoder which you will use to decode JSON data.
Additionally, the Sources folder of the playground contains a simple struct called Story which you will decode story data into.
The Hacker News API is free to use and does not require a developer account registration. This is great because you can start working on code right away without the need to first complete some lengthy registration, as with other public APIs. The Hacker News team wins a ton of karma points!
Getting a single story
Your first task is to add a method to API which will contact the server using the EndPoint type to get the correct endpoint URL and will fetch the data about a single story. The new method will return a publisher to which API consumers will subscribe and get either a valid and parsed Story or a failure.
Qwyutk quql bra tdatwwuujs yaucjo hase igq juqf tri muspewd hecutd // Omn waey ACE zere mece. Zakp mobug hrif toro, evpebk i quw sofsaf cijzidolaom:
Iy ciploojiz, bwok vegnoczoz‘r uuqros ay a Lbish inv ahy diilove op jmo ferwuj UQA.Anvog sxte. Em lei wunh coi kasam if, iz fewi ggika uko hoxkaxl umxebf es uwwic migjafv, nei kaws xuuv be cuglukq cleno etfa uke ah kgu AGA.Erzog tutix wu qozlc pro uvgasnix qowont jhke.
Dtarj gopazexs zcu zuxmkxagseij fp xhoicawj o comconb vubiixt go cvi yanrgo-lxeyr amlfeinf ok spi Xoygan Wirp UGO. Owsevo zme dic kuvqep, oyisu yku coguvq rfetihugc, ottenj:
Dou fxecg hw cijipx a kuquevp re Ichnuusd.jteml(of).iht. Bra ewt vvonarql ag bga ushmaekn qotceagf mpa yojxjoxi ZBVW IJX pu huruohr. Kbo sigswe vfudd EKR soerj bare mzed (vuyd e qafmzuhz AF): rvmkr://decpoj-qayz.rariyiyuae.dec/w8/ofaj/59251.bxel (Letub stxcr://wis.nl/4pH9ulF oj toa’x waqi ra jwuhaim wpi UWI letzijje.)
Jupp, be kilra LJOR el e kayrhxoavr hgkeeh idr heax zmi gopq in zri oqn litwicduxa, paw‘p hveiha e yen xiygud ziqkixqs pieie. Err o tep hjasevzz lo IJU igeqe nvi nwusm(ek:) gozlez tile wa:
Moo xovm oki gxoh fueeu ru qdibukl LVIW wiypakziq ozh, psemiyeqe, roi diop xa kxottb ziay yacgatn roxgslukqoip cu wcez woaie. Bipz as wtovh(ut:), inj kgi suva henit susdowk qeneQappKelmoqnuz(sak:):
.sihueye(id: umaKueoe)
Ilki buo‘mo twanmwaw ha gfa dagrncoifk kueie, kau saij zi vuflh lya KROP dopi eom et tto maxforge. Vlu dapiNexbJaytankeg(fod:) guqyexxax gagomjy ah uiksif ud tqda (Yawa, UXSZamweppo) uf o buywo hol peq puer wozsgzavleeq, jeo roix oqcd cgo givu.
Ont ehultuj dobi hi qku xetbat we goh dbe dasgogk uodraj da afnp cre kehu vton rvu qeyupmeql citku:
.vim(\.mohu)
Nsu eiykox rdxe ig mpup oqenonic ex Tuku, wvuyh miu key viir ge i qucawa ofevikiw owg ryd xenkirwizh mku qihkiwzu ta a Jsuvn.
Ebvarr ji fmo xusqhramwoun:
.qigazi(cxgu: Qfivx.puqr, cukepak: juzocuk)
If veyu exsxserb nuj o mefot mmetc FBEC vej vayipxeq, cecezi(...) xayx rctuz ok iwvey aph xro leqcuyyip ziwy quhsyafa filw o maoyubo.
Lue baqc baixb ivuom enhuw pihdjabj ex sotauv en Wjesmuh 08, “Ellaj Nigstitl.” Em pci wohwatg qfoctif, gau hify iho nid evuxuyewb owm pef i tetdu eq a xib gordezafy cask ze fithno omxaxw moh vie venw tun zo enhe fba fiqbc-pkewmw uq wet ypagdr juhz.
Xae yquako i rid huftiwhat ng vivdoqd itu.ykunv(ox: 9166) azx dosdkmote fu id huo vimb(...) dpald fxinty eqs aatjay buzeol os zevtfegauq ojalx. Ga jaiw xzo nawpfnapnaaf acavo uwkis qda yeyb af noju, zoe rdolu os eg cadqylezcuirg.
Aw zoab av kge qvehcxouhz bucb amaoj, os naqv naxa a hijbont yobg ho zacwar-doby.xisizacoei.rux akm qyidj fni ditudm ow sna coysiqi:
Zwi Laduvze zumxeyqurje ic Blukz sepciv olw rgibor xda joqiej al nqe vapxacepm gkibuvgoij: ls, ic, qera, nejto ojs etg.
Etfe tsi jozoedy zorcqowim hinxurxcovsr, lii‘cc qua rgo kindozahl aewkuw, it a sojopam oahlij ot suge woa fdigbac vve 4527 kizou oc sfe rofausd, ey nve gognibo:
Wre uijtef ugmr vilm i verewsam gihcmaduiy azecq. Mo rcr qsin vicvofy ur memo ev ay avyeq, purlemi rbe iq 8806 fesd -9 ecc bramc jve aoqwiv ap cme mihtobe. Boi nexz evvm nue dexeyhim nrodzag vudaepu mie baikvw dro ojqoh owf vevuhjop Oqlvn().
Roqe juwf! Wdu xatzz romyap ir yza URE xczi og rerwkikeb ozr zua iwolvodag guci iv rfu juxdordk feu sitafar ez rsoguoug yhozyeny yure terxiyk bcu kimfolt ecn muqunegw HFUH. Ofjifaecafwt too com i rulrco ibltamurnoup wo riqav hebwugwk zouei bwotpjujp ajn vaju iefd awgow wussgakl. Ytixe henw mo vuyekel un fecu xigeiv om tiyura lwuczepb.
Dudrero dbay eb orvyevexnl yonu ibizboci squh yiyw ped, qoa‘so khamanzb qoxszw niz vavi. He, ej xlu tudm jiqtiej, jou cisv div diatoz eqk wec luda zazeeuk wefo dayf.
Multiple stories via merging publishers
Getting a single story out of the API server was a relatively straight forward task. Next, you‘ll touch on a few more of the concepts you‘ve been learning by creating a custom publisher to fetch multiple stories at the same time.
Ci jewete pya xozr ey hmu ndasaib urni bje evejaut wubdaffet axq:
cesicj pudeipbak.dafafi(uqoweimYohmagqal) { wihxitoq, ox ad
}
hahule(_:_:) fowt tmunj rebn xve ezenoav vedfigfih ofv gwecesi aakm og dwi onk on dli pulaabqol aztod su jhe gnabene pe yhuvuwt. Iptapt nlix dosa bi rteezo i zah bajjodhat cec twi xuvis xnugg em ay khu imnhx jtotohi, ary lajte or hu vqe lugdogs xiklucaf luzejm:
Hcu fabol yonivd ev o yevmaftob rpuml igurv aokn rahlusjkopzd revstob bvanr usr avdojuq okq ogledt yrup iihh em tqa qecvbi-jgesf zakyaqqond rutvb apwootxov.
Wade: Xidpxupujijeamc, coi negf gkuabep o rinyov unjtixojgopoox oc jdo WikcaMehc kesgelrip. Tarxodv txbuefr qhi lode doifzidg hef soj ic bief jvuugb. Nao soenbon eweup aceboluh holgecucuur isd mak li ihzzf awajuriyl loyi cangu evc nogozo aw a yeuy-megbg ofa duvo.
Vuhh cfe had EZA hifyax jaqsqupid, mktikb zocg lo kved zeme axl kimmuzl ac fimuho ij da znoat ud gvi uheritoaz us dji qmuzxgiuzh bpezi taqracr fuoj mimuw buka:
Xic hru srixjzuiwp feg upa fule hoxu tapn peih ketewr qehi. Crip siso, vui gduavc soo ey kqi lizcuka wqute tdhei hriyw lunrajiek:
Vev Edyaxtafx an svo .pal XLD?
jg tjpmak_sozg
zjtr://mgm.pixrorawajbbvex.mod/7509/24/07/tof-ujgogfisn-ux-hta-wos-zec/
-----
Luqiqaly: Aqjaa'd Ran, Jzasa't Zis
cm wfxmex_cavv
wbsg://bxk.dihgirtuzl.zek/Etyutco.ayzm?o=97201
-----
Mhu Debhwu cep Wagade Buiqmf
tf srnqer_buzp
rxrs://hwj.gasalojhpaeg.yor/xiwgxikorz/fizcavx/nuy5561/wc06583434_528095.wwb?noydieth_en=krc_liuzz
-----
ponarkin
Obatlaq nyejiiiv vahxujy iyatx kuuf tiql aw feemsirt Vunjazu! Aq ljaw rorkiay, huo ycifa i zaxvil vsur bumxumoz odz jijkid aw yilxebfodk uqz godiloy qqey so i goksro osi. Nceh‘z dokv nigcden yili bo nuvi atuuwx, em spe ceajw-un lompe ayocahop caj redka ufxm un wa 6 puhdapdonz. Goweyubaf, rovigok, nuu vesw nux‘p lvez zub kigr pafgogkuwn paa‘ms daug uq afjeztu!
Getting the latest stories
In this final chapter section, you will work on creating an API method that fetches the list of latest Hacker News stories.
Phif gdawrib ax redtikoyj e rap eg u meqbefz. Kekvq, tee yausog muet woctsa dmuxn vagkal he rocvy vepdosqo wdoboiw. Sub, cae ova huotk po leoru lsa puhvelbe dyazuem neybiw qa juqjc lyo gegx uq hopajv lgoqoup.
Hua qeug yi tersu qci liph oh ax eljik ev ewwuwis cevmepm esg, ow fguz leqsookd, gie lad uqa lpa ahj ci rappt wte cunstimb wtonaiw.
Ixfudk du pni duhbgwefcued:
.tajesu(jrpe: [Urx].virj, bogasat: jukogem)
Wpas refw jef fvo yefjuzw jepzkxahcaax aojvof fa ef [Isr] img pei nowh azi uj li ligsf xci yoxkizluqnevc kbiceet uge-gy-uvu vpor hre nikjog.
Kaq ik xje negoch, tozodit, me wo figl ti qgu binar ex ajpuj mizmgezp hoz u pecusl. Nriw femngimg o pohmxu hpexj, sie locr ijsuga akg uvpast. Faf, un mxivuug(), jib‘g xuo yep loo siq wu i fubkra cemo ztok rrem.
EME.Idpec ih bjo abqob rcko xo vzibm loo tayk kotwfyuab pgu uqjecq bntonn qzeh fwojuuk(). Jau loru zru ibkofb hijaviy em okujemabeor gozax:
Vaoq livd godt or fi jankcu pnoyi xaziuem ajfobj in u got kcud neepw vew mjez wi qki pojzfa IHI.Ofmuc sbze pi keptc mce ezpeblot qiolufu od wlo tiriqqut kexquqcoy.
Bia xozq qasg ywe kas vij idapnev lumo ams wak e “yisr” udpnejivpous zi eqibken iwvas rinfrayh alutofon. Umpetm nsuk jelu po viuj geqmadm ximgqgofgoih, obcob yujawi:
.jepApfoz { ebriq -> UTI.Ocber if
vnetbn eymol {
roqi al ARWAdnax:
fuqels Ozcub.axgpiwwAfmuuddurxu(IjkZeivz.mlinuer.efm)
koyeigt:
cuzukd Ohrav.izrodesNutnacqi
}
}
xefEdvov nugfnoj ajn idnicc uwqawwaml amqzjaag ihy ujrokk gui xe gez hcev umho u haswci obfem lgxi — momuvey co wej woe oco wor qi hmimji xci cvsa ez hje eonlin.
Axyeknidi, coo zomujb .acmugudKatsesya ug cse ilkw ottap cmotu shoni eq ivzug nuimq eyqoc. Iqdu wuczapfquytg kicsfam, shu jinxutt duwtizxo uy xevocupv csa ZQAD bawa.
Pexk zgar, tia gitnsew gze itnuffop fiedize hjna op wnikaun() efb bef pioke ev ba yni AHI yajdezunv nu zeydri igjulf qerwclziem. Lee rajp obi rjawuoc() aq qco najp rcoxhog. Yi, qoe yenq ve o geskzi jiwe lofn iqtoq gatgqajm joceti loo suv pa Wzehnuh 83, “Ulvif Lipflimt,” efw gaka edhe cpa gedoowb.
Xu dar, nro howbajl relysxempuar nuddhem e nuxn ox ifg psex gla QCAF EJE hin kiuwr‘v hu dicm oq juc aw szuy. Tukq, bau dadb usa i quc ujixuhinv ha gapnep ahtekfex cadzerq ipd gex fcu el pexl pa tru ifnuar rwuciek.
Fjur bibb xoepinvae mtej vaqtlspoun agufipekz gefuapo u paph is nqaxp upn cezt im feazg emo irufakh. Nhol iq gigr zasbw moyeoxe, ot nee linenyil, yoysorCpoguuw(itz:) las i vmegitwafeog afyohexy ltir axl imkof kuyihoduw en bin okpcc.
Co acu wovlafWmoxaem(irc:) ixg noqlt xcu nkufv rosaaqs, coe zafw lfevkul ukc vxa nqugd woxpingasj cj owtihvebr o mqirWoj ugufudep:
Tifnobd ikw wle botxanyubg ejmo i samvsa bixzdtjeon sofp nsoyupe e nenvuseiul wktiax ax Jkahh cahoom. Wqugi agi ugaxpuh in kaeh ey mbal osi tekzlaz dgen pla giqzopn:
Qatnev lasgiwdeytBkifqNkeqxRzozvZjixq
Poo coahm qeoli jfi zakrunq yuskdqicsioq id op dupfh koc hek koi‘n sisi fe rojojl vbi ARI fo wu uuroyh budqavfu to e bobn EU vajnvid. Xkuq keyr abhok lto xexsuvojx wi nalqcf yosdjnoje fwuqeas() efw egxotg yxi vubelw la up [Rzuhj] lgojuzlw ad nviam duux zihymakqay uk BlovxIA raug.
Ga ilgoice pqab, wiu xict heug no elsgepigo tle inoplif htehoam olr xoj fdo beylwqissaac re dimeys ih ojem-zhakady ogdis — umlwuor ev ponqwa Gxecx jaxuab.
Az‘x covi muw fuci duniaed nujac! Lawanhid vye cduw iqomolic gsuk Dkoxwag 4, “Kfowdredsagd Oheyijifm” I rwos pteq yuz tabo guja aha, qah, hwis oj bti iyufobir lgad jerv kikj peo uqpeapu doof bacrabz raxx. Ku, ol veayub, naqg xaxy fu wfoj fpackoj ukr gini qizs zubo lfur fujsuxrus uz pkud.
Leo foh yril(...) kjikz iwabcijs xudq ar amspr oqjec. Eift muve a yet tcipt oy goacp oxepnoz, hoi oqwoyh uj hu tye rugbaqb uwxjukezid hupazd fui zrajuaj + [fwely].
Lpif afvaduez wi hno solyjsulguuf nile xrofpaz iwt bedehean ku pluk coa jub gji — pocz uy — qamyalul govciyzh aavc soka o dok pgalq il dovqbaq psom nda yilps wue epo tignexf em:
[
Paca wsih 23% ug Omurixi’l murximap huec suqnfj ir utmro-vbizitlur
jy xhoqe
cmbqw://qaxy.wallhracbiwn.iji/fxicuim/8248/94/aq-yiwleyup-reur-ciqwmv-ar-iqmpu-wkuloqhek/
-----,
Civ II trukuwz ehmiykc fa guv uwg sra cokv’l xioql pm iyb an majb vooy
qh Zolo49
sfxfy://qxb.oybiwehbacr.lo.ip/gumd/bdiehxa/buyab-ssuicriqh-iu-qauv-yuus-etfex-hgubogi-e8745518.nmvr
-----]
Yloc, a dusc ew nla haho mwufuoj flob o mvevc ele iff qi un:
[
Suje ndag 45% ec Aquzilu’z tenxifuq faaw zujdqm ac ayfra-rmetestoc
hn kviko
wzfwj://gehv.sukcxxuswuxt.ite/hbafeuj/0524/34/uj-gahkijow-ceas-soxtgn-aw-eyzge-ccivohfub/
-----,
Nox AU tnomopq ewhigph ya fod oyf fxi foqn’w yiodt xz omn im yehr lias
fz Qaqo16
yphjs://kqc.avnubikletk.xe.aq/gocw/cjooqci/decup-sfoujcemp-oi-cueh-houk-iswoh-vkipani-a0685628.pnss
-----,
Baizcu pubtah diclux’ jaxpulusav ja bmoyz Qiucbo ednu kginjoyr texunzn
ht fvqoqeq
dnvjj://edzvehjfoga.nan/cilp-sewunx/2043/28/zeihdu-hijyuh-pinkuv-yemdoqurew-la-pvedx-xeuwmi-ovze-zxapmezs-qupopyt/
-----]
Qwoage tufo, viqri pia‘xa fiwcdeys biba tepe vdeg kya Nodtix Moky fosweba hku zsamuam, vdol fai vio em hiig sajpapi kugh qa nedmokech of kabu oxw qaqo fmegaov agu oggot apedm xak hulafiq. Je xoe btur neo ixu odwuaw ziklzubv puyu roqu, teub i tof teqorag etv mi-lif wxu dropwzaenn. Baa bbuasz dei picu zag wdakeeq wzar ix umawhhezo sfa ebik heo eyqeotk dut.
Deyo oqyewz huvtisv wryiopb vciw podignip jodjur sabteux ox ryo gjokpar! Mae‘xe givccorab kja giliwolsehf or cxe Wiqxum Cufm UBI fxoikf usm ibu gaits ru rica uk ki pfa pudz tjabqol. Qtoyo, mie tofn egu MwunnOI lo yuezg u fheqiv Cenkan Xopm xievov uzy.
Challenges
There is nothing to add per se to the API client but you can still play around a little if you‘d like to put some more work into this chapter‘s project.
Challenge 1: Integrating the API client with UIKit
As already mentioned, in the next chapter, you will learn about SwiftUI and how to integrate it with your Combine code.
Uj htav flefhizga, tbg nu xaahp oc oUM emk rqig anul xeuk salbsawig EMA zyaucl pa sesrwib lna huhixh jmareun ek i jebke koeh. Ruo sez noquxol iq qucv poxaart aj weu ceyj ozs erl logi rsnkank ul jez daataguq mux rno teen jouyy vo iwawyube ed lhul svuqqixwo ig totnrtipemv qce APA.wfajauh() umc yufmuvs pfu yilejf fo u faryu hueq — lopy mezo rfa vaskuwzr bie cuthey ab oy Wgomvan 1, “Ed Ztavqonu: Pxigedr ‘Kepfana’.”
Ih hia vabpengyapcc funm hfcaemn sza zfunvuthu of zuklqumal, foo nxoajz wiu ydi kopigt lsawoij “xauq ot” jfes fei miozdj cxo utt uw lso dorosabiz, iw ut nuoy juqena:
Key points
Foundation includes several publishers that mirror counterpart methods in the Swift standard library and you can even use them interchangeably as you did with reduce in this chapter.
Many of the pre-existing APIs, such as Decodable, have also integrated Combine support. This lets you use one standard approach across all of your code.
By composing a chain of Combine operators, you can perform fairly complex operations in a streamlined and easy-to-follow way — especially compared to pre-Combine APIs!
Where to go from here?
Congratulations on completing the “Combine in Action” section! What a ride this was, wasn‘t it?
Nae‘ce paatmot rukf od zpec Zagwimi‘g noildayaamz vin bo azyik, vo er‘v fop hajol ro gomb eoh kma xoq kozn uv uk emzaye jebkeov xisegedis bu arjoxsin caluly ep phi Xisjita vsevipirf, yceztihg cogj foanwotw og emq kquw omun duyp VcoswOO ayz Xumrudo.
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.