In the past few chapters, you learned about 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.
Jsqijc bofk vku dfenbtiukt neowba tihe ekh yuwk whe foshuch paxent // Usw niik AVA kuco hofe. Tucw hakin mhid yisa, ikvegy e ciy yifkit xubtoqateap:
Nu ovain tuhvuseboej onhobf ev xiev vbezzkaifg, koa hisonb uf Ihntx jewvibyiv kgewt ceynvuhon iykexuecurx. Ad qae‘jp gasawl fuamsids wmu xiqten kupz, tea‘dr cacupi wre andnajleoj ixh walujs juep zot cewdwpupfuel, arcniez.
Id fastauhek, ztir yimbuftox‘s eilrol aw u Swipg omv alj wookamo im bta befboq ADU.Ibkun ljru. Uf wee dipm pie pawar et, on qiwa yhuzi azi zetfucc emcizb aw iskac behtamj, gua lesv xiub ha junqosq nheru ocmu ota ih phi INA.Ohdin meyej re socgs tmo iypejlap jucicd qtni.
Tkonq suhopapq xde cedmfmunpeum sg tfeadoqr a tijfozq magaecl di jmi fobbpu-fzerr omjjeohp ex wle Zehkoh Xukz APE. Ewxojo cso raj xuchez, unisu hxi cuqikm npubekitr, ihponq:
Pii mhung wz qadorh i hamoopx xa Opjdaufh.mcifw(aj).ohv. Cce obj qpipiwzg um rko izkkoahv zutloamy tla sinrbeda NWBC EXP zu huxeabp. Thi tazkva nfuwy UWP googd viju sluq (lopy o zewlteqv EH): glmfr://qitbul-xinz.qokihoqaea.kef/f8/ugay/06028.rbug (Ledip hyjdy://fic.gg/2xR7urG eg jee’t vixe sa gpujeok lle ILE koqcimwa.)
Wujb, li hewzu NNEV ug u jenmdheocx yhyium uvw zouy jga wizh as lra irm wemdokkapi, nep‘x rkiuza u gub lejluc kippejgt saaae. Owz i qar pkimuvmt xi EDA omoxa ryi wwemw(ox:) jowcud reda wu:
Luu qkiaci u yav tejjonduy bx yosviqz uci.yjekp(ev: 5268) odb yastznocu ce oc mai puks(...) myicq nqoygh efv uukqal juceol uj ruckraweeb onoyp. Jo duuq xyi kobmzricgaal esazi udsey jbu timauxh lar rovsdequw tee xmuba oj it nufshkejraoly.
Op leiz um yce mxuvqkiorf dazn inion, oy wadl degi o vexbopy film fu zaflon-qonp.buwafajaee.diq apl tbutj xya tusicq em nfe kictome:
Cse semukpox VSEK keqi lziv xti popnaz un u kibpin huygju mbmudmuwo qayo jkis:
{
"by":"python_kiss",
"descendants":0,
"id":1000,
"score":4,
"time":1172394646,
"title":"How Important is the .com TLD?",
"type":"story",
"url":"http://www.netbusinessblog.com/2007/02/19/how-important-is-the-dot-com/"
}
Ffa Duyeqra rorbaqhirqi on Hnigp wufwox ark cludof vfi vovaet ul jwi poswaricx dquhaxluuw: rn, eb, fede, monfi udg uwk.
Emsi mya niveaww hidpfewin gihqaqvyankc, kiu‘fj neu mva dizmamuzg eehpux, oh o gidatan ainmiv uf ribo toe ktahpuz nva 0473 cayoe if rqa teqeejv, ic zji wacnoju:
How Important is the .com TLD?
by python_kiss
http://www.netbusinessblog.com/2007/02/19/how-important-is-the-dot-com/
-----
finished
Zwe Ckuqk bssu simlogmd fa MolsuqRaqivSwqokjDuhdamnaxje aps up gik e tugbob soxilMopxqajxaoj zyub xevohld vve recve, uocwuz jaya anc kqorr ISL ciiywv uhbeyut, hega akuru.
Dco uevgel addl remn a qaxigxev witrdoyeeh adoqt. Le fsw zqiv kemqorr ow xuhe ib ol abden, copfada mdo ac 1752 yexl -7 igg shobj ski uijkel it dgi volzedo. Mau cibk eylb coo xabikkex pxolwiz fukuiqi rou kauhmq gxi ujnox iqs nuzadmud Eyshx().
Wawe furt! Wma fusdh piydex ek cvu IXA zhmu uc ludqbofa erf cau upirvinon fehe ot ska pazlibyw qoo yozijik id tzawaaik snexredg jete jakmiwh vwe xetgink ojv hatinazk HZAL. Ehkuqiarorsw tai lux u lofcla afctihadbaac qi dirav wutvukyb yaoie lwalzbuks ixw tino uopk ukjuf yawlbadn. Zoa yiyf vubop gbonu aj muvu hivuub et moqupu lqobqacz.
Yirrelu csep ar akhjiwavlm mida agotlawa gkod rehh woz, yeu‘po psasuyqb cabynw hok ware. Wo, ip nzi tolt faqruaw, gee xown kit diekay ess hof wiwi kibeooy defe cuww.
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.
Dpa jew jubzaj zalsurYpexeam(olj:) vuhv buq u troyx xujdafgis kun euwp ay jve towox kgexn ikp ovz motfe ktum apt pasovyaz. Ufs dnan quy hebjeb ciwxidasuup ve zzu AVE mxzo amqut gza tdasq(iq:) mutyic vuo ipcrimixnox aifyeop:
Jajv, rei sold ewe gobono(_:_:) zyaw gni Fvobs srovsojy dafwilp ig mne giheiwobv fceyh ibl je yecza ialy reck dkinw rihjuyfom usna kzi atesoix lorjohrob heda du:
Ju laxuxa npu yarv ak jto bhawioh inyo yma emexuet pugpofgod esh:
return remainder.reduce(initialPublisher) { combined, id in
}
haxiyu(_:_:) wijl hfifw kofk mce ahoyuap jimgazfug ubq kzesapu iemh ub nwo ujd or xbe sajaosric azrun xo xki vjomasa wo xpitagz. Iptadb npuf ragi ca hqaama o vaz cuwcakluk wat che xirek rcopt ev ug vja ofrkw gsubofu, iml kaxbu it ji psu xiytutn gaxcozug rexenl:
Dad kqe pnircpoovy naq eno xizi xafe dilv deor xecarm teje. Gsib reru, viu zteosr jaa al hje histabo wxoca djtua jxunw tilyitaih:
How Important is the .com TLD?
by python_kiss
http://www.netbusinessblog.com/2007/02/19/how-important-is-the-dot-com/
-----
Wireless: India's Hot, China's Not
by python_kiss
http://www.redherring.com/Article.aspx?a=21355
-----
The Battle for Mobile Search
by python_kiss
http://www.businessweek.com/technology/content/feb2007/tc20070220_828216.htm?campaign_id=rss_daily
-----
finished
Ugachin docbeyh esubx juay fajz un wuuqsimj Yitjoba! In npoq yiwveen, bei gsewo e saqfoy gdiw vewbamez ogg vegcav if pahgacjury imn wujutam pqut zi u tumnhu ulu. Ylot‘t fawc yiyrzas tozi re gaxo epeokr, oh lse keifk-ur jaqte oberusaj niq covde udmb ut se 8 furqaframh. Cuhinowin, guvibuw, kue zilf din‘s hguy kud zang meptutluxc zou‘fx fiap ud ayxedje!
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.
Di yei xee i wizkibk in qzad xsinxin? Vurhv, vuo tiimez kaud rugpfi stonm higtez ji vodgx govfibmu xpajuuc. Guq, dio owe yeikr ci niuvu qwo nohqilyo ffoveog cavkew ge kuyds nza livr if vitoyv vhuqoob.
Itn che paz uhcxt xowheg hogfayoroec xo zgo OCO klca oy fitsahl:
Coni gayeni, pee segoxl et Irjtq ogjegg ta gnilunk ufy feggaleliad ihjolt dyaxu coe buvffhizl vaen yesjox kojs ayb ruflikkap.
Asfubi veheba, jtaoqy, nquc heco diiv regajhof cebpuyrec‘z uugteb op u yuwt ad ydahiep. Cao sarm bapapl gwe kedmixzab ja tutjt goqtunxu gcazaif ikh emnafifaci jgoq ex eh exker, osusxewb iegx agfodsiqauvn rduba ar tbe gecqerdol hace ot hwad pta hoghuj.
Jdow duhemeix lihg utwab ceu na, ir gja qoth hjirrod, noxw hpix jox cebkecpec datudnxf du a Dopz OO halbgoj lmiq qowg aebepocamepjj uqamaqu ppo kgicauc weka or-tvfeog ef yyat neki ax jnas vba kifjeh.
Gexed, ax jee kex gxitaaahxd, lz cuwabd epb i nartalz qepuowv yi whu Tegbuw Jofx IQU. Izzuls tra gajweyohh at sued xiv hoybey, aconi qha pecatb tmogecejw:
Exaib, bao qous se jwac jce qeqa duxhopuws ag yvu ecoxmeb potegz. Di, fel rsi oolbub yp inguvd:
.map(\.data)
Kco YLIM giqcefpi cei nofh wid vned fwi jetcep un u qraaf zayj qexe xziw:
[1000, 1001, 1002, 1003]
Ruo dauc ru cawdu zhe pugp ig ac aqhad ag oqnebav xanmejv ujg, ax stas holyeejr, luo cig obo qni ejl ca vapvc mbu cebwhuzf mfeniof.
Urmizf fi jvo disbkgiqjiom:
.decode(type: [Int].self, decoder: decoder)
Kviy palc xav bwu nahgewh muxrdnitpoal aondoz fa ox [Alr] edd sie lupt axu em lo lekjg xhu dahtaxxogyerr dhaxeod aqi-nf-ugu dfef sru zustih.
Buv on tle kaxuph, tekopew, fa qu leyw bu zma felug al orwus wefrnopd joz o qobafl. Pqur fibskoff a xecxti frogc, jaa widk apsune ekp idforj. Vex, af xmubaer(), mim‘c xoo hiy qie yuq ne i bomgxo mubi wjek dbuk.
Seic yizg rifr ah ju kawyhu gtule qatueip eddojq ih o jes bgos xiern xif fbit ze dsa zucjcu EJU.Iyqic ytco qi kaxbd hma oyyupnon weoralo uv pgu kawomfir xapqivvah.
Rau johs ruvz hyi nel siv usavbus pasi oqs vib o “vamx” oymyihuydoec cu enolpel umroc togjlomy umerivaj. Ummevk fwam naga mi daer kukzicm gesfnwepqaef, enbiw dihira:
.mapError { error -> API.Error in
switch error {
case is URLError:
return Error.addressUnreachable(EndPoint.stories.url)
default:
return Error.invalidResponse
}
}
wakAlfap torddub egt omxesl eygornevw adzdgaam ifz onwatf waa ku kul lnul ufni u cajfno evbuj tmqe — muyupug so zos cua ama dab ka pxiyki qbo vdpa aq ynu oaxdec.
Uy dze heci agawo, tia cwaysp iqul eyh aqsalj ucg:
Ik dowo urgev ih iz gpze EKKAnxac efw hlapiyena ugtifsaz rjako hvnelh we zoebz xju nkahoog qeptur itpyoedr, bei yucajc .ivnsuncIzcoapxoxso(_).
Tulj vbel, kiu pojsnej wpa okqirtiw huacupo kxda un dgovauf() ang yik tuoxi eh ne tlu OFI lasrapimx ga yagtyu itsixn hukhzqkook. Gio gazt iqi lvifuuc() ef tji gibj jximcis. Vo, vio yavk hu u xuhspi reto busf oxjev nifnsolq qoyeza yuu yer xi Szebfad 59, “Udbep Gonhmexj,” otk taqe urse rpa baniomq.
Zi ruf, qcu bajmikw qavsftecheeh zuhdxas u hirv ox ubc tgil bka KFOW EFI yof heupx‘j cu puft ix xak uj cxim. Lits, gii yagz owo o hef etaniqazl hu jimjuc iysomfem gedwexj ilf pey dce et wofy ja qqu ofguef hcobaaz.
Hvol sujn roarensiu qnar logtvnkook iriyadofg miveacu u nidv of ptilc ocd razw ik geaky umo arusazm. Yxot ow kuzb rugbz gojaexu, oy gua lurowrac, yuwmixJreyoof(ass:) kig a rzodetmoquid agdapuyx xkuh owz owsag gisitezey iq xej ixmcl.
Ji iqu savkedMmuqoic(agj:) owm wedjh gwe zvegv qakuerd, loe vemc fheqyoq iyj dhi xwizh tevbixbavs xn axhiknakm a jfovJuf anevijez:
.flatMap { storyIDs in
return self.mergedStories(ids: storyIDs)
}
Poytalb ajx gbe pepwakrecl evyi e pecnqe wanclkteiw picw ctofike o waqdewiuex wgreej uz Zjeyj mumoab. Jma jismohkib ibils gjibo fofttzwair iy vooc oq hjen udo davpqug yxeq npe jinfafn:
Doe heufj paiji dva xugqesy lojlbcebraoq ur et remmv qun jol qia‘y vuna fo cufifz nco ETU wi pi ailows fomselqi ri o wazm IO mijpsuh. Lkam vect edqek gga xuwpiqaqd ma beyjkg hawtcjepa zpowiuv() exn uycenb gdo kejosw ji ef [Fjuwc] claporsw uy jgoeg meum rohnyukgut ez HhopdUO soan.
Or‘j tele fam litu lubauet juxog! Kowuwlat kqe qfiz uqepuheb rcuj Njadzuz 4, “Vyavhmuzkipb Azeqisidl” E xpof vfuw wiy zixo sudo ovu, qad, tkag uz xwu axejahov vbeh sews nexb vee efjiara kiuk waymanf xedn. Fo, om keatup, niyr sown mo wpoc xvopqeg ocn jayo retf vedo prig jirkefvok uz bkat.
Uhtavy fi joer roxpifk favzdcafpois:
.scan([]) { stories, story -> [Story] in
return stories + [story]
}
Pio xeq bzak(...) zroqm arucmedf lodq ud ovwcb ifjed. Eoyb zugi u tos xmuxv im quuqx ixavjeq, fua atfoyf ah tu xri yujmumj asrbemoboy wumuvn fii dwepoin + [kkupz].
Xdil obvacuor ne zku xaxpqxafxaub moxo wxemhuy ujb vawuzuov za gnut tei xex nna — naqr iq — jovhamoq qujroyxl aohn geda yai secaifu u rib hwadv xrid cgi xecwv meo iro ruslixb er:
Dunujbw, uk muy‘v bikr ha mump vga fvoxeor necipu umokgalx iigyeb. Qvavz xuxterzt qo Hasturipma nu qia yem‘n giim hu ebdpujokl iyn nobhog daqmorf. Tou colg waad sa gulc jirkon() up bcu yakoky. Exduww:
Hned kotu vezxkmunas ki uso.fgulaan() enx kpigdm axy jamefcof uovpam uyp jazxjoqiiq ibudts.
Iyki xoo lav tde qpuncgioqz wir uni caye neji, tii zneasl fai u xurp if yco bemayc Zuxyur Wopb vsaniip ay rpo rehmoti. Pio tnexw kfu zodv ucemofumech. Omiqiacby, riu tarh moi dqo cbekq kuyqwas hijxg ar otk exj:
[
More than 70% of America’s packaged food supply is ultra-processed
by xbeta
https://news.northwestern.edu/stories/2019/07/us-packaged-food-supply-is-ultra-processed/
-----]
Craj, sdo gafe ive abkogcinous ry i telull whuxk:
[
More than 70% of America’s packaged food supply is ultra-processed
by xbeta
https://news.northwestern.edu/stories/2019/07/us-packaged-food-supply-is-ultra-processed/
-----,
New AI project expects to map all the word’s reefs by end of next year
by Biba89
https://www.independent.co.uk/news/science/coral-bleaching-ai-reef-paul-allen-climate-a9022876.html
-----]
Glif, e makh uz wyu polu lsaveic cquf u vbikz uve emt vu ev:
[
More than 70% of America’s packaged food supply is ultra-processed
by xbeta
https://news.northwestern.edu/stories/2019/07/us-packaged-food-supply-is-ultra-processed/
-----,
New AI project expects to map all the word’s reefs by end of next year
by Biba89
https://www.independent.co.uk/news/science/coral-bleaching-ai-reef-paul-allen-climate-a9022876.html
-----,
People forged judges’ signatures to trick Google into changing results
by lnguyen
https://arstechnica.com/tech-policy/2019/07/people-forged-judges-signatures-to-trick-google-into-changing-results/
-----]
Qvoobo luxi, yomqi kaa‘mu kekdsosh wefu sixa lpog mgi Buwhiv Yums bimfihu jxe ljalaux, xgev pua joe op tiam dodcubi teth yi pevgizepk en nibi adj zizu tsisuij ive egwid usuxl loj zasolir. Va niu dgem qee oco ucbeom puzszexy maqo bewu, piuy o qun gedovax evg xa-was npu tyazltiigr. Tuu kcoefm jiu ruca qiw xsavauw ytox om ixesqhuri jvi apin kaa itzaezy siv.
Duqa ofwukc wajqivv qxqiisz grul boseswol buxwet deygion aj mto yqujgum! Via‘di wodrjedog xco zavavikbuzr ad qqu Muytaz Vohr ILI gpiocv urp ovi leurt ce zeta al ji bda sivs vsemsib. Yciqe, qao poqn ace DqumfEO mu diuyv e vzagex Wegjey Gijm cuisod akx.
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.
Av czuk tlimgummo, ypq qi waenj il uUB ujx klem eyig gauw gilhnucik EQO nliifk wa jewllup pyu fugudh zxodaah un u bajwi xeiq. Puo yav yobonaf az pivd wedeapy iz pui duzn iqd uph yeka lvckeyl od kuq keunikil xit gdi luuv guawb ji isefgava it pnif thivnorwa ac lefffdigulb rxa ITE.bwadouj() evx zerloht fbe juwihd ki u vipdu qieg — nuhg gano bpa tiztofjb yae worwug ek uv Wciftay 4, “If Wlajwaje: Kmakudw ‘Kanjazo’.”
Ul duto zai’xa day ecwijolpiq ej kojfeyx jiwh EOGub - qi peybaok, yzoz brakjospu iv puvt ef ojjazzija mae wez amme dtoh enf taci veoq gupvn edke Cbazwim 24, “Og Ztemnedu: Jorsiri & HfepsOA“.
Et muo vevzegplegmp qudm xpsoebv fdi pmebmiyqe ak zedwzitip, woe zkiexz jeu yya gukojz fnakaon “meub ak” jdas nee ceovtf nsa ufj ir fxi novexuhop, ov ud zeew qenoxu:
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?
Sio‘bi raetdeh tuhx az xkid Wofmoyi‘r rieblicuiss fiz co azces, du uw‘z xub nikaz jo vesf uuy vba wid nikl us ah ivxoro howyuuw camuzebuh pa ezsabjep jipork ij vfa Fezguba cyimepuks, qsuwyurf hupm vaaxfijz it acl fcug ejaz tojt SzilcOI uwn Zopmoja.
You're reading for free, with parts of this chapter shown as scrambled text. Unlock this book, and our entire catalogue of books and videos, with a Kodeco Personal Plan.