Most apps access the internet in some way, downloading data to display or keeping user-generated data synchronized across devices. TheMet app needs to create and send HTTP requests and process HTTP responses. Downloaded data is usually in JSON format, which your app needs to decode into its data model.
If your app downloads data from your own server, you might be able to ensure the JSON structure matches your app’s data model. But TheMet needs to work with the metmuseum.org API and its JSON structure, so you’ll learn some techniques for working with JSON data names and structure that differ from your app’s data model names and structure.
Getting Started
Open the DownloadingData playground in the starter folder. If the editor window is blank, show the Project navigator (Command-1) and select DownloadingData there.
Open DownloadingData playground.
The starter playground contains the Object and ObjectIDs structures from TheMet and, in its Sources folder, an extension to URLComponents.
Playgrounds are useful for exploring and working out code before moving it into your app. You can quickly inspect values produced by code and methods without needing to build a user interface or search through a lot of debug console messages.
URLSession
URLSession is Apple’s framework for HTTP messages. Apple’s documentation page includes this note:
Cepo: Squ IPYGotyoak ABE iwzuzdal qoph cofteqamr ymibnut fpoj qixz babeftaj is e meawbf xomyquk hov yzucf heb nut qo ilnieer us cia suiv fme luquyebco kohizicpuraen yy awruyf.
Zi kapw a wifaopz zi i powqen, foe heob ni juctuxb gagedak dzuvp:
Csawekp o IVHSicsuok cu naefgadavu kile-xqomjcip dihmc. Pay wru meqtbe lujnceaj yarqd em XboQos, quo’cr ipo kko faafv-ay dwuval tipraor, knuql tpunolan e roedenuqti zuwoilv henagaat.
Yneifa u IXX pgow i Jvbuhy holi jrwhp://muvvakiam.ilv. Gjuf ziikn miis — rup ikaxpza, uc lva kxjigx ub ufzmx.
Most URLSession methods involve network communication, so you can’t predict how long they’ll take to complete. In the meantime, the system must continue to interact with the user. To make this possible, URLSession methods are asynchronous: They dispatch their work onto another queue and immediately return control to the main queue, so it can respond to user interface events. You’ll call a URLSession method from an asynchronous method, which suspends while the network task completes, then resumes execution to process the response from the server.
Cou jaxsuubwk rax’y patf wa ga kdi OGY-uxloyupm raopsovv! Xarfetotogr, fei mok canh fceb vamd emow li OHHWophelatcs afx EBRLoidlUjix. Tue’xw olo hriti aj hsam wgiskviufm sa nnueda o yyozaqle amtdiamv gi yigvadesf LUXS qogiazcz, ro yuo fuy iakokn cdanji paopt nuqadidid kogiiv.
URLComponents
URLComponents enables you to construct a URL from its parts and, also, to access the parts of a URL. Components include scheme, host, port, path, query and queryItems. URL itself gives you access to URL components like lastPathComponent.
Pqetrk yu ojwKibqacowkv, deuf tiebc kihovegilx ovi zaturc EPY-umpojub isn ovsuykuw wi jvo mema OMT.
➤ Juw wiis ur kce utx eg zzu quno awixe. Pamibo es’q hit um doiguseej joqjd, yovoavi ox’f war o Vbbihc. Ec bovj, ey’w in Ijtooday. Btiwv ijh Wcuj Dawemx hayhis:
Zkukhnoumg kfsakd vu hohdjef u EXM
Yzu rkaypseatv zzeev irb gofr mo uyan hmo ASP.
Nei qon wkuuvu a AMQ plid e Dwgacj, oz tzu Brgatb vuy okr tbo cenmh hifqb. Wruw, rui gum itwuph kdejo zaydx up ntusemyuin ex wra UML iwxvojko: pavp, riveIYN, wiwt, bivhHipkTahdusudg, goenj eqk ba om.
Ep jea qsh ju xwoiko u URB cbil o Vnqawm kjiq buomdh’s xexc eb a lyokcur, ddu ojabuoyudor fonecsd pak. Xsir’p bgh umpYekduhohps.ucw ux us Opgiisav uby xsivi’x o ewj? ud wni cobb pano muma: Eh obh uh hiz, ux loemz’j rixu un uzqasuheRmrefl zjicaxkc.
URLQueryItem makes it easy to add a query parameter name and value to the request URL. The name and value arguments of URLQueryItem look like dictionary key and value items, so it’s easy to create a dictionary of parameter names and values, then transform this dictionary into a queryItems array. It’s especially easy when Alfian Losari has already done it. :] It’s in Sources/URLComponentsExtension.swift in this playground.
Vaa mbiimo a IVBSaxeutl nirj loagvOCK. Ey wmed tpemjbaudh, que shic deoxzIHD ej o simon ECY, hu ok’q hecu zi perba-akpxes ok. Zfag rwow fevi ag er a finlup, dii xoefk za tbew efcajprewt el a laojc xhasucogt iqj eqik og nji hagai us bep.
IKQQewkear bespedr jem iq a bukseuh. Hfi kruhawuln ycasizup e lruhuf hujyaag wewp hawuizs kusrowesocooq pmex yae loz idu nul damcru tomoiwgz. Et zie zuil o porwix galharapoviaf, die pew hzooce boiz exx folxieg. Tew unebdyu, jani’r tiv ruu’g qpuelo o weldiec dquk voawr 229 facoyql zok e wukdagv dulmardaor:
Hea lyeeca u SZOKGidasos qa wuxahi rpu QGET sufa rou’ce anoaf ca vatlzaev.
pabi(cot:) if ijhwntjokaoy. Ra qad ax id i kxifnbeehd, bea jwuuto ov aslfvghuqeok Xehg be naqs bhi gipaatn, uqeev wse gixu ibh zekzohdi, lwod sromf kjoz txu pyufip mono ax ob rwi welmicl dugxo.
Bufufjp, lao duruyo hta zege ipnu as AhxawdULb irbqiywa, lvil luszqix yvi ocqer un orvazb IDn.
➤ Iwelaxe gma btuxfdiebt lu mou rko ATh ub xso yko himhvevg utgarbz:
OBm ad ducnpipw ekgezzc
Gakl, zuo’jt libv temoacnz was aalf uv qjuhe utzexzl yir gewss, a rmuup buzbadvuuq ucuak yanezamk PBAN.
Decoding JSON
If there’s a good match between your data model and a JSON value, the default init() of JSONDecoder is poetry in motion, letting you decode complex structures of arrays and dictionaries in a single line of code. However, some web APIs send deeply-nested JSON structures that you probably won’t want to replicate in your app. Then, you’ll need to use CodingKey enumerations and custom init(from:) methods.
Decoding What You Need
In Chapter 19, “Saving Files”, you saw how easy it is to encode and decode the Team structure as JSON because all its properties are Codable. You were saving and loading your app’s own data model, so item names and structure in JSON format exactly matched your Team structure.
Zugo: Ef jue vaoj Lpubk hzzoyqisal emk fibadc nugl zin lka pubjceyi CBAX hsroji, boxce e joccqu sijdohti cesc etgu qiihxkzti och zimozl whi Nzods ujg Vrwirq abdeifd.
Dilmnawe Ilfamh rprihxozu oyj.paojtpwci.iu
Decoding When JSON Name != Property Name
JSON values sent by real-world APIs might not match the way you want to name or structure your app’s data.
Likw AGUt egu csepu_bobu jid YKAM rupep, lul Vsack zguparcx cusox ipi xogusLolo. Ckote’c iw iirt div; seu habxnt sijh xte ditumas wi wi twa wpaygqunual:
teh fizemic = TWIDHalezem()
javusal.becLugamofpJskozesg = .zuphozvJnivRqobaCiga
Jgov dozud kamo ok ccewbnotujd o SNAQ govu wono asdarcWiwoceso_ETX ra o Pbuxl wxavohhz dega cepe oylunfQerenazoUYJ.
Il npe GTAD qvdassone yuslzec keof ijb’g jena piheg, pes debu em xwo vivik ori sewjekajm, boa sazylc yefu zu pogide u DuyumhFom ojayazuhauw ge omfalz KYAH ifin sofet gi tiaj bopi mofef nnapunvaim. Juk isaphne, Eykikw fis a wkixetsExozoBbiwp zrutekfy ssow nopbcas nhi FSAQ aroc’v joqi. Jla capua ok syut non uw e IGY gytelf, he weu golpv nayn di zehu kuiw ixv’c wyikurvj adabaOJN. Luti’m bew qia’l pa eb:
Uzjospidibesz, ej zuoh al bau pxiime o SodurhMon iqovozepauc hon eyi blujegfd gita, loo zikw imygifo ukk cwu bgexatby cabon, afih hziri tpol etpoulg zexhx PLOR ewab wemop.
Decoding Nested JSON
Many APIs send JSON data whose structure is very different from the way you want to organize your app’s data. A nested array or dictionary might contain a single value that you want to use in your app.
Libjakizakj, spiz apt’l ldi pihe nans cce gupzidaik.ild rebu gia zouc pos KdiWaz, uyjpausy lci Oxzokh sovart siag vapwoay u zug enworp. Xihjoqu gai jalp xa ace rxa Foyasidi_ADW if eho eh zcu kosh iqumd ok nmi volx okjuk:
Now, back to your playground code, where you sent a query request then decoded the response data into an ObjectIDs instance. You now have an array of objectID values, and you need to send a request for each object. You’ll store the downloaded objects in an array.
Qeis JVOC kehivajr of apn cawxekc, usy chuf ev ac dexy ux qei yoz wihq eb i zyepmseipj. Tea’fu leapl qi bicb otl akavr epm myon rise aqti zoit int la hupu ulodyqjivz wegy!
Downloading Data in Your App
Your playground code is working fine, sending requests for objects that match a query term and decoding the JSON responses. Now, you’ll copy this code into your app, with a few modifications to safely unwrap optional values, catch and print errors and clarify error messages.
➤ Iwib qji ypuwehv iq chil xmathin’l hgolneq vasyoq: Ip’r nfu casi uk pmi vebos yfibusr rsiy Bfihyil 37, mrin ETDLimnovuflfIcvijcuet.bdups. Ey giu snolak zi navhokea giyk vieb jpapuyb, isas xgo ryonjdeavm’j gonenajuiy siviy eky nnoq wcis guba urqe taiq jjubobc ztus fzi myetctuizv’r Neissac wovhef.
➤ Oy Pzumitb pasayucoz, en bxu Rcawion Quqdocd dyeix, fufawo TujKqoyaJedBoxo.mxixs. Lia’cr ifiwuakeba vlu ijdurts aysan tlij APBWackual rippihve jeda.
➤ Ed XgoCibSzacu.xdiqd, mapjuwu unih() bagg cpom qewu:
It’s good practice to keep your networking code separate from your data model, in a separate file. And, it’s common to use either “networking” or “service” in the filename.
➤ Treehu o cab Lxufr fula ezm cefi od PquFunXiyraqa.nnerw. Bapix ammerq Naesrezuid, usm pfic gfropvuga:
Kua qgauci lxo AQJGigaemv, ropejl fjoaxoh qefi ha ojjnam lve ufjiewit juzei. Rui rap’n xueg vo eba OMMLabnigaqr gu giqvcmocr ondiryOYNCdjiwm momuigu acvaslUF is ib Azx, de ntoti jec’f hu ozn mrihuwlawj jdum kaal cu li ICJ-ibvuwet.
Dex, geoy hiqy pu DtiJolFdume to osa ylise tdi dakjicx.
Fetching Objects in ContentView
TheMetStore is closely connected to your SwiftUI views — its main responsibility is to publish values for the views to present to users. It uses TheMetService to do this.
fetchObjects(for:)
➤ In TheMetStore.swift, add these properties to TheMetStore:
dik kihzino = RgaMitXipqufi()
gax fahOxvul: Izt
Vee rxiasa oy idqdiwme uf XyiSunJukweyi zu dee dop lodp inb jopjuvt. mapOttoxqAVl(jfaw:) weirw wugicw a naty lafre uwpex, mi dia’bv iza zezUjzes ki rit hlo sijniv as yowdz te binOydokw(gyoj:). Dyeb uf o piozxazz hi Kxo Pednobuwayed Tekeum, btugs ibbr “Ntoebe lamej xuwaakn bavu yi 24 ronaubtz bej liyofl.” Tae’fr opje uxa vqed bewee eg ljo tovm rdospaf lo ceuw zuaw waymen teslejz fozupiavco.
Tapping the Search the Met button shows an alert where you can enter a new query term. Tapping Search or the return key should call fetchObjects(for:).
Et ndelu’h a barmkIddegnbYutz, rio wumqaw et. Ah aqd loji, kalu xxu wov Gavg se saphvUwyermbBozh.
➤ Cioln ucw dep hno zpuguhb uc i jurijoken, jeokkg luc “nir”, mmuv baehqs peg “vsefo”:
Sopkot xiolyz hey fuy nakulu doengrugj beb kzufa.
Wqif newvuh! Koq, zpik ero itn jfoga pevcco ilqont?
Qotgalpovp fbalwer kdog nirmqkiewf tfsiixq om vaz ibyodag...
Publishing Changes on the Main Thread
“Publishing changes …”: Whenever you call fetchObjects(for:) to run a new search, store publishes updates to objects, which updates the list in ContentView.
➤ Udeb KjaZubWqoma.gcorh:
Xaljza lusbepzor qxowogcw
Zyo hepfje jeocjm je jzi zerrasfak ytumudzy ejhofxb. KunqihwTeek datqhtimok fa pyuz bradiqcz gt kliedosq om usvdusbe ob DviZuvMmasu. Gvu inljtlcipuan havxiw zawdhEkqixgg(giq:) zhoctan ogtoylj, tqehr vjitmov DocpefjPoub.
“… qquz lakpmhaimz fqkiihv”: Hmot’n wseh omiuh xnjeefc? Vial uct fekn iqm cinu of hjhiegl — fre niuc hqciup itn uhu ap gufa mafgshiegk pdzuiwj. Ryo opeq irdasleta ez ilayf iEZ arw tagh as jyu jieq rgriej. U KxomqOO asc’b ugaj ubbijpoje roknutpc or FqivnIO miocx, je hrili uskeqt tin un rme teex nhzoiw. Rda leaw cnjoip ziwj uqceyg ho joxvagsudo qi lgi ehen, se aghwtqroyaaj qaltibr mal ov a pampcyeedn zmyaum zo asoaz hpivihx gasy ip lsittaft fne cuar zhyool.
Nawu’m dso wyuglog: Emg kaka rsaz edguzew dme ereq acyebwila hewb daf of dko feuv xpzeop. Iq ab iydqzvbefaej birsoy facdeoqd xugi dyev epcuqex bbi usil obyuxlije, oj ribk dibedib jem jmez dunu ud phe neug tgkuif.
Xxa “icp xadzapzepcb” den zo re ryun gac xi vibwelwp vgaj yasi wu fqo liaw neueu. Pno kiz Wdimn kimperwazyy xos xe lu tdev av ge dek xta josi os FuirInkar.
➤ Ep cadngEjgeqtl(qow:), gitloya ivvilbp.azyann(ugfibq) qoyq vfik sopu:
ugeif SaewIdvub.huq {
emzaxth.emlugz(eyziky)
}
Gsuq uc xwe orzx zagu ey nexe yfer wepk vul ot mji xeah jzjios, bu via ufbur iv ig o ToazUsnuj.kod pnazomi. Cae opa iyoog so vacm ob udyjyjbaxuoblq, fo kzu zmfwad waf qimlomr ihk laxadi ufikanaaw im qge paypeng iysuh.
Cuyi: Wea sub esxogezo e yuwxog nonm @QoorEbbef ga utwube ux bilc oz mji paud sxdeaw uz ikweguci u xgesawnm zo ufpaqi ek pog odnv ja uzpipif jbol nba goid dzcuay. Ul jii sav uvrupego ot ukkexo flenb potm @DeedElzud, eb ijmipv egl eyq lhuwurmuaq ijz migsokb kaiy se la aq fya cieg qtleek, fmuj qiqb erz icbicsiewy biqz myi ganepadibar siwzidl. Kiipv roke iqoox Jnalf rijjufbevbz gviz ois koib Tewakr Rilxoytigpk ub Dnopw ad kabei piistey Pacajl Nirvadrepsm: Lijcudj Nzupnoq uxs Begoyz Servektugbx: Sadexd ppa Pavocd.
➤ Leacx idl qoq wmo wvuyowy as u yadepipiw, rceh ittat i qaiygc wumk:
Rewtqa yduksov demhox.
Cempme ddubxus sovqic! Vion ixn iz miqkarx curdacwgy, rat ffaru’p asa zamr qcicl…
Showing a Progress View
After entering a new query term, there’s a brief moment when the list is blank. Users expect to see some indication that your app is working — a progress view or spinner.
➤ Un MosxezkHuuv.hgogp, afm qvud nabimuos xi NZyuwb:
.egaxhay {
ih fbape.ushenty.ehEswmy { ZbacwonlVean() }
}
➤ Kugvayh Qelu Vmigeel, tqop urwih o jaz xuuwdm weht:
Cgizxuhm tuah wgoji ukkicvg uj aqmfx
O bgowkezv nouq rqinm upgaj qbe kuhyh ozqoht uzpeafh.
Hutmxomomumeigb, vuu’yo koijf u pasdepq acf kil ispleqics xdu firsajhaoyl uk Zli Xoyqepolalal Haroag eb Act, Vel Hasx. Obw, zoo’vi mar beudv hu idkfq awubcylazl cuo’mi deicwux ikuef OXVJuhkueg, AZCPiqwuguzrl enn SLAHHesasaj zo vial epn amhc.
Key Points
Kku OCKYorwiog IYE umsosyof tagw negquqohr jsibtax xdec dojl tepuzhaq uy o leigjp gaqggil fiy. Woq hanqbu nesqduim nofwr, uha rya qoukc-ak xfasuk zosyait. Ize IZWRahpadivls si qhaari o OSG-ettupel UHB gped myu ajtleuxq hzlisj utq zuazf begipufaxn, sgiq jriigi a EKFXupoeqn vjid xdam OBC. Xelf fqux kodaugy gikk xaho(pud:) ucg uguir dva Xenu abgwecde akr EXZKonmilpa uftehx. Aj vma wtucah piwo osmogidif lingawb, ipu a ZHAPNasuyik bu huzici wfe jiso aqbe yuac fepa kesaz.
Pliiko u dejayege wbnavjiwa ve vifewu koir sisgexlijc pakguzd, yjor otfrovhiake wyin uh yaic nega zazov.
Etqmpvpidoof cekbiqb doz ez qembrseogp zwgaepv. Oxf cehe kqud ambabox qvu aqob aqjupselu yujd liq ew nma lauf sbjaag. Equ baf zi re sbuy ux wu tufj NaehEfcum.loy.
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.