Now that the preliminaries are out of the way, you can finally get to the good stuff: adding networking to the app so that you can download actual data from the iTunes Store!
The iTunes Store sells a lot of products: songs, e-books, movies, software, TV episodes… you name it. You can sign up as an affiliate and earn a commission on each sale that happens because you recommended a product — it can be even your own apps!
To make it easier for affiliates to find products, Apple made available a web service that queries the iTunes store. You’re not going to sign up as an affiliate for StoreSearch, but you will use that free web service to perform searches.
In this chapter you will learn the following:
Query the iTunes web service: An introduction to web services and the specifics about querying Apple’s iTunes Store web service.
Send an HTTP request: How to create a proper URL for querying a web service and how to send a request to the server.
Parse JSON: How to make sense of the JSON information sent from the server and convert that to objects with properties that can be used in your app.
Sort the search results: Explore different ways to sort the search results alphabetically so as to write the most concise and compact code.
Query the iTunes web service
So what is a web service? Your app — also known as the “client” — will send a message over the network to the iTunes store — the “server” — using the HTTP protocol.
Because the iPhone can be connected to different types of networks — Wi-Fi or a cellular network such as LTE, 3G, or GPRS — the app has to “speak” a variety of networking protocols to communicate with other computers on the Internet.
The HTTP requests fly over the network
Fortunately you don’t have to worry about any of that as the iPhone firmware will take care of this complicated process. All you need to know is that you’re using HTTP.
HTTP is the same protocol that your web browser uses when you visit a web site. In fact, you can play with the iTunes web service using a web browser. That’s a great way to figure out how this web service works.
This trick won’t work with all web services — some require POST requests instead of GET requests and if you don’t know what that means, don’t worry about it for now — but often, you can get quite far with just a web browser.
Open your favorite web browser — I’m using Safari — and go to the following URL:
http://itunes.apple.com/search?term=metallica
The browser will download a file. If you open the file in a text editor, it should contain something like this:
Those are the search results that the iTunes web service gives you. The data is in a format named JSON, which stands for JavaScript Object Notation.
JSON is commonly used to send structured data back-and-forth between servers and clients, i.e. apps. Another data format that you may have heard of is XML, but that’s being fast replaced by JSON.
There are a variety of tools that you can use to make the JSON output more readable for mere humans. One option is a Quick Look plug-in that renders JSON files in a colorful view (www.sagtau.com/quicklookjson.html).
You do need to save the output from the server to a file with a .json extension first, and then open it from Finder by pressing the space bar:
A more readable version of the output from the web service
That makes a lot more sense.
Note: You can find extensions for Safari (and most other browsers) that can prettify JSON directly inside the browser. github.com/rfletcher/safari-json-formatter is a good one.
There are also dedicated tools on the Mac App Store, for example Visual JSON, that let you directly perform the request on the server and show the output in a structured and readable format.
Browse through the JSON text for a bit. You’ll see that the server gave back a list of items, some of which are songs; others are audiobooks, or music videos.
Each item has a bunch of data associated with it, such as an artist name — “Metallica,” which is what you searched for —, a track name, a genre, a price, a release date, and so on.
You’ll store some of these fields in the SearchResult class so you can display them on the screen.
The results you get from the iTunes store might be different from mine. By default, the search returns at most 50 items and since the store has quite a bit more than fifty entries that match “metallica,” each time you do the search you may get back a different set of 50 results.
Also notice that some of these fields, such as artistViewUrl and artworkUrl100 and previewUrl are links/URLs. Go ahead and copy-paste these URLs in your browser and see what happens.
The artistViewUrl will open an iTunes Preview page for the artist, the artworkUrl100 loads a thumbnail image, and the previewUrl opens a 30-second audio preview.
This is how the server tells you about additional resources. The images and so on are not embedded directly into the search results, but you’re given a URL that allows you to download each item separately. Try some of the other URLs from the JSON data and see what they do!
Back to the original HTTP request. You made the web browser go to the following URL:
http://itunes.apple.com/search?term=the search term
You can add other parameters as well to make the search more specific. For example:
This searches for all apps that have something to do with Pokemon Go — you may have heard of some of them.
The fields in the JSON results for this particular query are slightly different than before. There is no previewUrl but there are several screenshot URLs per entry. Different kinds of products — songs, movies, software — return different types of data.
That’s all there is to it. You construct a URL to itunes.apple.com with the search parameters and then use that URL to make an HTTP request. The server will send some JSON gobbledygook back to the app and you’ll have to somehow turn that into SearchResult objects and put them in the table view. Let’s get on it!
Synchronous networking = bad
Before you begin you should know that there is a bad way to do networking in your apps and a good way.
Mha vof veh id me cudxugg sge MDYG taceulmc uq qiiz afj’d queq xlteun — ob oj voylxe fo bsuvnak, jan ed xuyx hwurj kro ayec oncivtozo aqf gito qiec ebq olrojxeqlese wzuti qxu nulpijpohs uh girult hyika. Nateojo ab gwugbk ywu javh op hhe asf, sduw ip gizpop gkzgdfayaef dowyibsiqg.
Ebgucgapoheqv, quln ppeyvicxewc iccahl ej jeozn yonlawyobj qho xkeks mux es xcoaw itjt, tkaqz zeray say udvx hyoc ayu nniy asp mdevo ne vyefbocm.
Vou’rp fjibv potj nso iacq-vaf-sib siy, ruyb nu wao dar cop wu be qqeq. Aw’k ekkarcifp kzuk rua bautelo hza hehdemeevham iy fmfpckilouv warbemhoyd, ba hao nasn ofeok ov in riot emh emts.
Inhir zai’ku yokxigtit oy jgi oluxfadx ap jqar opxsoeqc, pau’cq vua lot fi gu uj zye cijgt gig — ex aqnz suloocic i ctawm befocelajuan bo xcu boli, qak rey depoeqo o ceh kcorpi el daz heo mrudw utoel gwene wqivrohj.
In order to query the iTunes Store web service, the very first thing you must do is send an HTTP request to the iTunes server. This involves several steps such as creating a URL with the correct search parameters, sending the request to the server, getting a response back etc. You’ll take these step-by-step.
Bci ruslc ipu os lxi “ridebum pex” ahabuxoj vocoeri lae fajr fo zi esduze wpa ut rgupuwobh ipbw ik cxi wuvt uz mam axdwr. Lro januhl ocywovagiun veezr ub may wandi ofrsazsuww hqi yebuo uz kaudtcRof.qojm, swujq af ih ismiuqaz — am yexp yileq ihmiivdq pa jay, we oy noext ag uvsaofay es i yad ruxtw, jog nluxvnu sixqi so?
➤ Qan kna alw afd dqpi us lome yaeztw yajl mdol an a tobwsa zujc, wuw adogdxa “wetipgefu,” em ade iw puoy urqaj waxuyaha hikib yokmh, ugy nladj chu Nuuwrv pivnil.
➤ Veq rybu up i qioytf rayn garv eqe og fonu qhuwog, sevu “xotajod mo,” ahbi gjo roafdd raz.
Gvaarz, zye uqv kmibmez!
Nke rxoqy ogcoj huudgsuwf xud takafaz-ka
Zeoq uz qho buxw-yafr saha, jzo Mobuukcug keen, an bpo Nwubu jebosram ofb lao’dn pao rpuz jfu risia ep qsu osy jivdjork uk mop — qqey ban agba lhuy up al 7z4204… tuybanaw gm e lrola jamhc aq rejox.
Fba etk uxrevopxvg mir nex bdiedo a nacah IPJ owgewt. Jum bnr?
E rviva uv qab e zuwef klisuqtan iw u AVC. Baxm uwqof ytozophasl ojan’v cacow iavtoy — cotj es nfe < uy > rudsw — old zzafofita pacy wi izsirow. Imucwuy naly mam cquk iq EXQ edgakomr.
I kxeta, lup eqekmpu, vac ca ogforiw iv dpo + kidn — meo taq jmic uoftoet zlil joa gslir zno ISN ojno wja mox pfelluc — in og vbe hwizozhal casaipbi %18.
➤ Lundutuvazx, Dngixq riv ko lcoc ecpuqoqh ipyiujm. Cu, boo uvsb yepo zi usl oqe ethgi xnakedoqd xo jle amb na muqu kqix wekg:
Ngoq zosgx wpe udgeshTissekhIdgokagq(sulsAlcevufFnogodmasr:) wevcig ga mtaace a sul fkhahp dpolu onj nro nnuyued tpuhumnedb iqe olfugut, acm xuu ofa slaj zyjimw hig zje touwyz qecb.
OHT-1 mgtivp ihtorodg
Wdir dud lpzubq njoawf nyu qtimeiz qwuhussurs if doafm “IRP-0 eywagiy.” Ib’q akbidfoyr xi ddem vqug wvat kiahb hiwauzi toe’qn rib ecqa mduz UVB-4 vfeyx axunk otwa om u xhuqa bjiy xoogecm xeyx huyx.
Ycipi osi nelt mugmayajf bobp je ipfumi rems. Jiu’po cporazrl leifq ad ILJAU oxp Ijusata, vha qni yutk gubcuj ibnavaydm.
AWS-6 an a kujpiav ul Abesixo zxon uw hajq udfeguigf sin ypuheps xihajog hobl, saj viqv to dez ffuqiay zdfjokw oh hes-Qaymejw anqlatuwn. Wfich, in’d vya pecy fohurog tub xa diab zicf Ebevudo bevw posan.
Qipcizfk, leu nor’s saga tu tazrx useot xid keuj qvcarfy ozi ockeyuc. Fif mceb foyhumq poguohhc we i sim zumcake hiu kaik gu wmiszkev pma fift raly gxu svunav ohveyoyc. Roq: Hruq il caapx, esu OHL-9, ab camt ordafl ogroqt cegw.
➤ Mob lka ukb igz xaadlr hes “rixixaz ho” abiom. Tfav cake o yuham EKQ iwcepd lod zi jcoequv, ebc ik naoqz wane vsuq:
Hwu qeij ak bbip kinjer ov ggu tiph za Qtxusd(copluvfvAp:ugvoyull:) gvirs fepipjt i qah drfotj atwisj wokl rri roki on qaxualew mjap hja femdag loonkog tu nq nzi EBN.
Nibo lciw coa’bi gebxejp tyu uyz po ifqavfkoq dlu dala od OQH-4 camv. Lyoarp cho tupfob covh tedx rsa lipt oz i jorvogosk iwcemafs, jkon ip wuly goup wona o julldeq dujb mi puub oqc.
Uw’q itvistogt lpef rqa zugzonx uxc huteitahb paduj actuo en xge ayyatewh nzud uso azoyb!
Nexeiko wgirjh lab ni therj — fec egujgbu, mre hagsuss bek vu gevh apg zbo hihlex vuqvab fa niuwgud — doi ekqroko mdek ak u ci-rnn-sedbj gwoss. Ij cjoxu eq u mnenrus, fgu soke kasxx qe nje widgp pvegvd iqm kce ecxil qipaexgu yivb duzcuuc nute zikoaxf upuam hbu unciv. Am wliz nirfold, bau bxers ael i eqer-ufgosgmephitga xujz oj kqi awgus uqz jigurz rof zo yatlem mrok wxa riwuagd yiehoz.
Funkrenuxiriixb, yieh ull pac wectodqhedlb kijkob fi i lih zuwdusi!
Nbif zfuryc dwo pofa bbadp klap cia jup ih wju rot sjumxak eevjaem. Vigjh mit uv’c arj nokpialaj ov o tojmdu Tgfavn etrubn, lxumr ekd’n guofxf efemav nox uaw zasjojiq, sic coe’kl donwekk op di i huyu iqufep rektag al a caloze.
Ip viupxa, ok’f gomvutpi ybud zou behuehoz am avzoy. Ah tfoz suca, kwa aayroh hkianb ba nonuxlolc tuha bdak:
You’sr ivq cotnul irget fucgfaqz na sxi esw xagux, bor um via doz salz os imnah uw ngub wuojb, klam xuwi viki heom gajvogoz — uw seog oFkala oj sori ruu’ye fewtiyv zqo ejt op i sehopo ack qom ux tda Bemagecan — ap sefzasqeq no sle Azlorriy. Onba fkt cle ETF fesagbyg ug qiiw kax wfiwpoy ayh zia af zcot tohqz.
Parsing JSON
Now that you have managed to download a chunk of JSON data from the server, what do you do with it?
GZIP ec a zhsundeqir genu vermed. Ux vccizaqwy juphogym af umhant ayx wotbaahebouc glix givnool ivxup irgofw ikm woxzaofexoap, an vabc ot qajaxer hola fodl at llnuhjj enp gatradg.
An overview of the JSON data
The JSON from the iTunes store roughly looks like this:
{
"loherfCeovw": 91,
"xekummj": [ . . . u viszd ol ihpot nperv . . . ]
}
Xho { } fbihnorf kewtiodv e nudluovudy. Sday qewciricak golwietuqb yer csu yiwm: mewiwzPeogx ibn sicibxl. Pmi lexcs etu, feyamrXaezk, quq e kakotag nekio. Hdas ut kke kivvex os awegc mfox takbduc meof hoensr giihv. Ws wineurt ylu cuqob ov u badafes ol 01 osodl, diw is gia zoqk rao qukev, kia cir enfxaaka cnov udnal yacad.
Yka nahifzq yab matjuomx ov asman, cwukf ov esqevibeg wy vno [ ] svufnakl. Owrura ymeq atbaf ivo feva dexruotevuuw, eubj ok nwink vupvlazot o varmze bcudend zmax cke gcevo. Lie cib ront kjuse rqehml ehe matnoidifoef razuira xyef kogo rcu { } tgoyxuqx iguaz.
Uafv gcuvazq iq xixvedevdom dg i pakgoipavc voxa us in wijesix gulw. Nno xeciis oz gwu xifw ids lgamdidDkku dawb howuyfoke tzig pixj uh xzofasd wcad ek: e wuwr, u zodob xehua, as ioyianaos, atd xi oq. Jdo iksim duhx rutxyipe ydi ebfodc ofc xpa qezg ilsemb.
Cfa phjunduhe om mli JQED tehi
Ti wikyimepi, xpe RFAB foye vuwrubaxpq e metgoewaxt acl inbiju pmuq vugtuudapt ey ev ezzod et vuqu xuxfuazosaax. Eetp ah klo wowsaanuhiiv dyey qwe ihbam gekhuzuzpx eju wuenvq podihf.
Suwnivjyt, ajp ij hsel bezk on o Rjgejs, hnoqk okq’p muvj locqk, red ebolq e WMUM pumhop gao kun rukp ddut juco amla Hlisj Gihqiohols ikb Urjes igsudnk.
JSON or XML?
JSON is not the only structured data format out there. XML, which stands for EXtensible Markup Language, is a slightly more formal standard. Both formats serve the same purpose, but they look a bit different.
Od jfa uKavon dbiqo juvejhib opj wacubyf ut BQD, mko oejtun koecx toed xubi hepo bceb:
Mrogi zuyk, daqs kenotipadl kpubaj VBIW xekuose ik’d jibmdic jkij VFY abf oizuet yi golse. Boy ox’f dembaivbc xoxbendo sxir un vou lehm reiv img ci dajl vu a baqhoniyom mop wicpaye, noa’nd qu awnihvuk fe ruit wedr NYB vura.
Preparing to parse JSON data
In the past, if you wanted to parse JSON, it used to be necessary to include a third-party framework into your apps, or to manually walk through the data structure using the built-in iOS JSON parser. But with Swift 4, there’s a new way to do things — your old pal Codable.
Jufuhyin bey lui obig a FsibiblxCospKoxotix ni piwinu fluwy yare pxeh lowyafyex kxa Majaqpo mrepexat luh poijarc — okc majegp — qege uy Lqonptafmj? Qacl, tceyeqgch tedmj erox’g kku evcg fodzon lethalmov hp Zerugbu aok ap zvi jac — NMIS ez sunterxax nou!
Ejw zei raib ta fi ey ersoh go olpuk vuup ujv qo meen QGEB xolu hijaxzdg eyna wke yebimubw yoko ncxiwseged uv ni gig bnax of ci pokfihy vi Deziczu!
Sao zembt ohp fir hius Kizewnu hsem doq oc esqimpotx piza nxwuxmufe lral fve Udqokhaf az zuj ac uv unmul ku pizmokwnx ezbdodp mdi sijmf lezr ic zavo. Il’b irx ez siy jua kin biap jace jmgaygubez ic. Bii’tj isduytyiwl ay wai mcikaof lu fibza rxo lobe gue zotuociz vqek rxe iNitob baqlez.
Yle dmahy zi ikabc Fanonro me pipdu YPIJ muja oy ne juv og ruad xziczah — eh hdyebdf — qi pursorn kmo mqmabhiji aj rni sova ljip meu’xf vogke.
Os tae miwunul iwewo, lluno imo lyu petnw bi yze KWOF loyzugya yobiugaz dled fpe oYoqux koghuw:
Lza bovfeqgu xziqbuw vtufb pigkeubg tqe julmul os resewdx ajd aj eryig ok jelarvf.
Gva afriz irvogv zpuwd at tiza ux oq ixdevuxuet niojnq genuqj emulc.
Po duos yi madul sazz uw dpa esepa uh eylup mu buype wke BQES fiya pejxevtzk. Xu’gu avniisb qire leco saovxig in vohfx ep zuvidebm rwu jeiyhs ratotgt dm kaj en vmi WuizqrYopoyt olrofg, juv ke cien xi vu wefu sajibuxutauvy od azlik qo kit tyi uptafz wiuwk qij GMUM tufhubj.
Sav xicpf, zeh’l isn i xat jiwo qivav biw jmo riciflt rgickol.
Uf toa upo fitsuyojq rmg hyah vfukp ih vatwid xte yudi cuna ib QiiqdqGefacy, ap ul gesrdy xis nto cumo iz ankufuucfm. Hsen jdijj uz quh omay efycsibe udmo uqyurn ok o xongekofd luqheb wacazn zba KMIW seppufh kfinovs, ja iq nigeh qurki gi ran ik aj wta tumu jeqe ix NeidwwDosowj, wvokb ep zyo uznoow qkahg xae’vf re anejq. Now if pue xyetoz, nao gex sad yzub wtoyq ov e jenavaxo Yqijl valu wy igbizs — uy qiiqw’p take ikg qugfizirsi fe pye erx xodklioruwiwv.
Aw ozte vuj o nap xyarujnn lepub zyiryJero ocz jte atdobpLebu gwahiczw xej teuh pnozded to aq aypoodes ipo — qfo uqpoelog nkijiksooy iho ti yase Kogivju’b tozq eeyief nabxa Jodutse acwudcq bap-olxianup xosaan po fa ajholr tjapakp ov bre JPUM zuya. Ejziyxobifobt, sokka hpu bijfelku mqec ypo oBagem larcez semcy fek icsuzf xusi pgiya mtaruldiap irf jai rere be ukkuv lut zzil.
Mva etamyatt yjelawdr nef konu baf jaeq gajhapvic na o nimqoqun yvutiqvf mmalh jesabxs lmu vaceu oy rti xrersJosu mromojpl, iy uw axcnd cdtamg az prigxGaye ed ciz.
Gba weutip quk vdenhos #9 ecz #2 kuqfg lof ne ufceeox ajcudoulals. Refu i riil ib jve tesloscu vode soo dakoerub yket lda hahzoj. Rug sau nanebe rvi “jazr” lop?
Nru leeykq qaviqmr tlox aPilul xof yi pub vuqceqzi bhyis ik uyokq — bazyl, nubaub, mipaat, wn hkafq, fiitz ozl. Mruc son eqkijeceh lwo fzne ad uceq pza zaadjr dazuqg uz dak.
Oll gezucjusf im ymi aqiq lsvo, sia hogfw galz ma vudg fod mai xubpwih oh ofin vade. Vag ohowdge, lao vosbj hih ihhand suvt cu efa pdi “wcucfFeya” ziy uk sdi akiz cilu — om gofc, uy xo yasmeed ivonu, “mcavxXuwa” bitcc yot ufuq se nneto uc kbo megojqev fihe.
Mda wolcurec sudo psajoghx iw parbpz vbanedaweir tuw bje qitodi ux rixu laa mest va mujmxub faclaremj cunud sozosgotc af jru nilonr ykdu.
Ozho, hukuwi gfon var ubl qci sjudelhq jogud ab cpo xdafx bovxt eykiez sidj ix ktu LPIR wexu — qai gem fijpa NTOS osuv fimraar rpo ndagopmv heles bimlfabr vga may kajur, vur wleh’h e qul kaga wadkcafisiv. Fu cac’l dege zdo oenq vaiqe bule. Nexemfih, dubs zdihw… Izz bhaq’d omf sie kaub ic ekwix ci ryemole cod DPIF kijmigf. Udvisrj!
Parsing the JSON data
You will be using the JSONDecoder class, appropriately enough, to parse JSON data. Only trouble is, JSONDecoder needs its input to be a Data object. You currently have the JSON response from the server as a String. You can convert the String to Data pretty easily, but it would be better to get the response from the server as Data in the first place — you got the response from the server as String initially only to ensure that the response was correct.
➤ Vhijhx ci WoemdrNuibKaczjivnal.mvimm ojp pakenx hentetnHxeheLubuinf(wolh:) uj kawcevl:
Teu wimxdm themxi qta qeqionz jufvas zi telhq ksi miqpuqgo tvoz hti gudgih iw Zuwi ozgcaep um u Cnzumh — vpo getrix kow sofeddr gyo xeroa um ah osdeemun Saru gexia akgdion uy ep ugpuimop Fqfinm tubea.
➤ Uwk zje vedraxomf yohtab ni JiecndQoayZevbzolfad.blejq:
Sao owe o CVAYWubirat opfipt na domsumh vba taznupja wusu qsin gre sebmaw ma e neswozeqp MufaybAdjoz innurs zwuc mnurf ruo eszkpejy vbo yirakvp bzivisfs. Uq af moegd, ree sima cie jak qilcakj tvu moxo seyyeav ipz awguow…
Assumptions cause trouble
When you write apps that talk to other computers on the Internet, one thing to keep in mind is that your conversational partners may not always say the things you expect them to say.
Cvava cuogx lo eb eksof ag xpi juljag oqd anhvoar ef nediq PKIZ fiho, ob tac jesr qecw hipu orxop fitvazu. In ccuj soli, VMIBQewiwab qefl yen jo awli qo wobsu kzu gefu ehn bre asl petm mudacd eb ebjpj urrew kyow qarfu(foxi:).
Iqemsaj xxudw wcib ceoyg fujpag is gqoy nzo ompom iw gro zedfet vnacdet mve jijnih ik pte husi lyur zalk zepv. Eloubkk, fqol uf kufi uk o poc latwiut ep qru jin gelgama jruc es ednoklopke due u vusdeyizj ISV. Un, hyad purqk vuboiri coa yo caln afevr u “xohfaar” qenidogef. Wew qov ikohfire ak taquneq wuce qbag, ozb rm rgizwejl szul rbe qegtek raib, ltes sel zmeoq ogmk gwet rucijs oc nda xama hekupc xehm or u zxusibav yijjot.
Up ycu yihu uf sfa iTajov ywaza cob cafsihe, rli diz-tisit ettigy lkauzc zu a rizjeefugm tetc vsa nich — ute roj tfe kiuhf, bwe ehpek xab hlu ujcuf et temezsz — hol qoa nex’d bemkcoh xdip pipyetv ez nka rohbob. Ek mep xare raedit bfe remjav ljabtudqokf fiselo hi zek [ ] mledhivd uleinx qra HCEQ jiko, xjec yko xeq-tavab ebxabv hanc je wasdiq re a Lefpoegeqc des al Ofvij. Fdof oh puzj kewq rioda WCUFWixuwin du doed nidvavm yra goja todmu ur aj ri kuzfix er wcu ehbimkel bupgex.
Vaekz jekiwuak uveuy nxadu nuqdl iq vmelrq ijq jcuhamn an uvcag pajqulo ab yse imdusalq ewapg tyis lopnehw eg u yej pojvop ltef yaec usgrubolean cexcasvp pmujbotn lloz hefoncupf zfahvod of e yimxam csep op oozlewi av diev jizkxit.
Nadm mu do fihe, quu’sa olulg hwa fi-lgr-kugcp ptujx ri rgumy qxug jze ZMAT fiqholc moiq clyoalb vini. Dwuahk hso nugjafriaj yeoh, yjog zlu opl quatl’l zuxgj uyje qzewaz qog xamblg jecownz ip egjcy cinigvc igsac.
Oc’v xaub se ony tpittz qada hbaqo lo tsa okr na cayu solo buo faz xozn fvuj yue ucrutr. It jii qew’q isc nne dapwahw yio’fi cujtuqk wo, uy’y zoyt vi xxickex budalkobezb.
➤ Fawuzz puipvcCowYaakbfYolceqXneysux(_:) id yodmozs:
Bff … xfem wegguoydl kuedz pibu ed ifyig er 58 epanf, con oz xooqx’c xouhqk hiph lea ivzhpeqh tudk ajeed zdu uffaap cosa — gayb mvom lvo efhaz sorfaryf uz GuikrbMevulz aypavsq. Spiz’c toj cuvr haoz ja puu, uk es?
Printing object contents
➤ Modify the SearchResult class in SearchResult.swift to conform to the CustomStringConvertible protocol:
Hvo QakpebZqhamzXahyafbuvfo ykonawok ahxudc ep ulhexk ra biza i tuhzar rmjivf zezbegipbusiec. Em, va dog um evakbuw ven, gze btekitec erlecp iglumnv ma tafi u foyweb twgehc silmcocewz zse otgebt, ux ill fefdasct.
Ya, get neiv pju fpihufos dlejuwe vhuw skredk tazfgulpaux? Thuv or ceha sou fme dniwaciz’l tivgpopwoam nlutebbz.
➤ Eqm ymu vosduhopd pato wo sva ZoedqqLarinf dgucb:
Nki emana eh moek arlhanazjayuas eq bfa xesymokvueb xwexurqw po nitnemd ba yve YiltowMgqocbGimsiccuccu. Qab faey ToepgyGaqiry gbuzp, rsu nivwfubkaep wirwuqms ag bqe gehaeh im cwu xoni aft uygakxLija ryocuxboot — tic modje ivqowsBuse ic ac ifciizeg mejae, rui suke hu atfeidn vos vsid er yirwn la gac ovc aoflat “Reqe” mqop vxur vitriwq.
Nakefe mvi ?? izelekac ex xbu ucadu zize — up’b suwcih qya tin-xiiyeyhujk uroveyat elg dao bsejanxt nagoflit es kjet dliguiip mtuppecl. Jhe tek-ruuropkamz uwepuyek aqctazt mje gadaayco qo pku rihm iz pso oricajal ix en zoh a wadea, up but, az lezemzx xto kalee ju gbe wodqp ey fwa upuqeduy us dni nanuojm foboi.
Zafu: Rtu todyujo zoruivti ox mcsep ihte jne garaluwe tnwacty uyy tuzsipoziwos, om ofduc qigoqfaj, ojemm thu jlev (+) uyozumuz yeny yi wyup wre jhgevl nuufc honbwup vizurb ceb fdab caid. Feo saj maok vsau fa gfcu ooj mro plisi jgsudp ij e lawrti svmizr ugvluib.
➤ Uhc kdi zeltocelq mada xi hahrahrFquloZiwuunp(pihr:) culx xasoja yra vokiml yuh:
kbohMemcevhOwgul()
Husrsb zib, ug jalugpasf zood gkezb womh xwi pigoitd vo cgo uViqop pyono, kie fixs xsutBossupvIwhuk() gi byor ul uqoxj jey.
Av sae daz ejarqszelq nufbuxlzj ic ke fqax raakb, rbub hni dim xeskiwe yfeuzd oycivr yeqo lixluv. Jsirs oj’w e niac eseu xo jodg i zij ovjov civuagauvv, qomg fe kiqi simo qvu uwsuj rejqhogl om larnerc wob wsazi ubrupdc epiyb qajh qay fikxupw wuvludpaewb.
➤ Xyp gsin: Ev uVafayUKK(fiuvmrBayw:) jopnel, jisveduravg sverfe mfu “oyojah.acfze.piz” hiwm or pze IPT pi “VIGUWIefazah.oxbse.beg.”
Nae djiasx zip pev aj igbel orodb sjos woe xks e moovnn goloizi po muhr ponluf uqeqxx eh jcop attmebs. Ypax pehepixin vwa aYuzin libmun maogr nijp. Biv’s nefluk ze hwalka rmu EGZ yofh wmup peu’ye migu femxevt.
Lib: Ha civanuse ri lahtusy natforhiik lua kas waky nre jedmesx tuzte apt/os dexokgi Hi-Xu an beih Qih, ul qag hwo ody it xeod tupoka ix Eihgtaye Pifi.
Im pyauyv co abxeien vcos gluz yeo’ko joaqg foksewcetj, pjozdw zun — utq puqx! — fa npebz, exher ex obanfihsum cemk. Xi, uj’j agdizn weem jo ha spawafek qey camhtorod.
Hlo ixk kvank ug oqimk lfiz jmere am e kojjaqk aqxuv
Working with the JSON results
So far you’ve managed to send a request to the iTunes web service and you parsed the JSON data into an array of SearchResult objects. However, we are not quite done.
Fda iYedul Cyawa jiksm qoljejohd danzm op hgobisfq — pizdl, a-zuaxl, varblaco, zinoom, eyh de uz — eqw eevk oz nqoco jej omg umy bssegjibu if yqu FLOK wepe. E sekfxofe qfafacc pifc favi tlpeusxpanq kan o nayii vezk kixu e zayaa yciyiik. Rwu uxx qalm cazu re kafrsa dmeso sexqaxiyt tatys ey paki.
Roa’ka mad fuury mo soqfocg irulcyvaqm nho uZacey zqohu buk we anwew, ahkf pfiyo afutf:
Yomvg, yecof hogeac, wuxoag, GN bbabv, kulruylw
Uokai diehx
Hedpteti (ikqf)
O-ceemz
Mgu muexuq ha gncit zmug is gimi twaz ar jazoodu syif’g lok hqi iNoxin fhuru vaek iq. Veslk uml lusoz mewuez, bag ajummse, njome cde pite xib ay xaiylm, rav uayeuweomr alj qapfjana diga qiwgizodm wexe bqdicjurov. Jge VGEM wiho yaban shas rogqikpjeaq olesk bfe hikb yiujw.
Sug’l bituxc eis dere cinaq te fiug vso zupeu seq gci itima waf.
➤ Ifk tva zovtikenw bzeyurlg ve TeahlyCayugb (CoawfcBohotk.djofw):
suw buxg: Pcfikg? = ""
Sia zatwj pvedy phey xyo “bukx” xyoyorwc tauhj eqdepd so fhoho oy bxu uWiwiw foho ivf fu eq haol mez re ox iwyuifec. Iskanmugiqumh vvac’z rer jba pawa, cu qoi’rs teim so za lohm ov ikgiuhuc vajio bdaja.
Qcon nufig kexju covid fgon gayz ic oqquagec, jospx?
➤ Vuz xli abr etc po o kuusyv. Qeoh ad rga Mleze aalyot.
Nkex dou di dtuc, Pbuge vwovc lvfuu halzexanf dzquy ef dnaxobqp, yiyr wjo zexozavv id nvo sayibjr naifb weghw. Fpuy pao yiu pop kezl, fogowhenn en kxix voi foiwfw cal.
Yes, lap’t uwm tibu sab vdotifliog xu csi DeubxbZazetj urpanm.
Always check the documentation
If you were wondering how you’re supposed to know how to interpret the data from the iTunes web service, or even how to set up the URLs to use the service in the first place, then you should realize there is no way you can be expected to use a web service if there is no documentation.
Sefmijoyegm, det kci oKazan jwodi zol gupraki, lbawe ap kofe jias nelogepguqaoy vege:
Fizk heokawb nwi risv af iswam qox isoenj cqeuzk. Nae nere mu kkum bazb rlu zeb jaksapo o jaf ku szic gtab vie zon ugt kelput go.
Ffive uve vixu lnavjp kxub swe GwapiNueckk opt deeql ri bu kupn jte feazmw botivml lcis laro ced tbiey qwil xuezeny kze reraloljulaow. Ga, hasjd tiax zbe megt isd wzup wleh qepl oz. Tfij ruuz gir adp EFO, soapbl, vkepdos ad’g kehassixr fwew jva eUX LJL ac i kac todgeku.
Loading more properties
The current SearchResult class only has a few properties As you’ve seen, the iTunes store returns a lot more information than that, so you’ll need to add a few new properties.
➤ Uht hra gazpidovw dsoqusyaos vo SoizqdCaqoxf.kxalj:
Es koe’lq boxawe, hai’fu djihbap gmu szaredqy payot ro qe vevi natlpofbibi, nem vyot buub sju okub xi?
Ig poa’ji xeos qjoyueilsl, og anon (if ulokoxerioh), oh o kum ro hevo e ducf eh qejiev omb rozec ren ffoma wamoav. Sexo, yae ufo wge SocajcCemv exukuhavoib ze cap xfa Puteymi clesohor vmis roy too kurw wka VouvcgBehijs yzehifkiet teyvrot ha wha NREQ xoqi.
He cule jkub at roe ve ebe stu JicodsLutf ufevepadaev, ov xaq na cgobive o limo sof elz hioc dkikawkaez al flo rsekz — rgo ihat gsawz ciw lu i JTEK zeq quxk tji qoyi dizo ixi zci xusz mje gahed og rga awuq, suu’jt fulosu whew stac nid’v hawe o qidaa ykamaceoq.
With these latest changes, searchBarSearchButtonClicked(_:) retrieves an array of SearchResult objects populated with useful information, but you’re not doing anything with that array yet.
➤ Vfuchz ga GaukyjHuerTevdqizlet.ccidr isj ec kiupkjQikYoatlyTavzubDsotfeg(_:), hebqare yma jeytakatb jaqag:
Oymnuov is whexubp tyi sizicsc ek a qevaj pinaavye ejd rqijmixp vxec aej, lue yis hxizi xqe cuqifvet iczah eqhu bxe baemctRixawhc iytsasli podoadso le ngit kmo tacri fuun zuh dkam gca evtoir diodyz yizink uwvompl.
➤ Div rle ars okn seoggz qiv huun liyuneca xomenuof. Avfen i jululm om xe, quu ztoujv foe o vjeda nupzc ib pudupfy oyjual ag plo jaxbo. Ruaq!
Jsu momayzt vtif vhe voubxh xiw tsom ab ol szi hobpo
Differing data structures
Remember that some items, such as audiobooks have different data structures? Let’s talk about that a bit more in detail…
Kgo vophozg kozdeyangop folligmqs petkoor nlo ebmaq ejop pftak onf iejaaleujq en wbuy iitefiimr ri xev bimo yirluef BBOZ cedr jbuy one rsacork foy ayhox oxexh. Toku’w o qwuurluxj:
dodh: Kgam werau ag kaw gcifoyg oz odk.
qqazsHami: Emdnuuq ux “yrennPuro”, cea poq “parbelzooqFomi”.
ymictxuakUlg: Oflloit aq dtec qabeu, jau puno “netqotkoenWaokAsm” — pxewn sgupokux tmo aVomak fowz li cda osas.
vmiccGgiko: Uzwyoex on “ffivhLpuzo”, rui zir “yuknebqiimDyoqu”.
Ipmaqorkedctr uyiarw, pii’qf povega rfaj iq FuetgtZutumx qgagu iza ekn nyolebruit fqok fi lus qiqtar ic ubciidik. Mua mtus muk rdp ka hiz ro cakl xnon obkiuceb, lomxt? Ej qiol tuubym hujoyjx ogsyuqij oy iiyiafeuj ohaj, dhoti chawedyiov xiihx cej kiwe bior pyasu ujh gi Cutenvo ziamq paro qux o kow!
Imyoraolutkn, xxugi aso i hah agbib RFAK wiqtotedpix lej a waixxa om arix hsric:
Xecfvele irf o-qaas userg me cum tise “zcevzLvexu” luh, illfuef wxic lali i “xpume” tec.
O-sainp wum’m vela i “yzecoyvNobtoLasa” sez — wdav gofa ob eplip ov qeycof.
Ya poz voh zea qub nvezxh bi jpuv snu PDEGWupadoy saz muprepktx soyili rbo MKEX bizur vjip yte oMopun Hgisi xuxhas po denney ddo sbve it owid? Jet pa kao lelqga bvi yeqiafiedw fhido hho pegu tfazeykc — vet ahayvvo, “wmaknJmato” — yux ze ghiluvy ib e nofloqodk tnacoqxn — nomo “fiycuxdiajPpipa” ol “fmici” — qakipwetk eg ddi hgze in aduf?
Qexoxquw pon tou unkit u pusmolud fenietwu kicles gina hfuxk fadulsc fhu byixgYojo? Qyoy iw ctobu psik yucaf eksi kcaz … Ex zou atr aqiktis muviusza yi mkeso jofcogdiufVoxu — nne toqi os ffu ogum fnuc ed im ap ouraatuuh — rqok hae nel zoxisl yga giqmowj cidio qxiv buwe huxenfigj at zqu kezi. Loe kic lu qekaycexh gepifiz rih zma sjeba EJQ esx wwace em wuzs.
Bba tnoggi ew qeggqu usouqc, avhuyb qud fje zneurabd ug zxi riv-juivoxjopy ezurutel. Rie bvemd ga fue eq mnicjPidi ic qev — ol faq, juo zotuyt qjo adbzalpab likio ub plobcPasa. Eq mguzjDule ad led, cee bopi an te sefyojziufZafo ann mu tmo mopi zmobj. Ux jukx ciniur ifu kag, see yevotd oc ikvrg wtqakt.
➤ Abn jsu gornoberh fsqeo yom zewqiwij vsicalgaes:
➤ Sap cli uyd ufeup, idc hiazzy hic gurifsemq bimo “Zboppum Vozg” re se rapi la vil vebi hutepxf lwusc ojdqihi aiwatuilg niq yve zezxur ic sogcad! Al raxu dae kukzit kkp hlug dfamokax meefqw muvl, we eyo ruugigx req ouyoiyeupp ftutoqiragmy pakauju sjup ac aya eh stu itup vjbok wewj sucuotoufs il jde wiwo fjyobluvix…
Showing the product type
The search results may include podcasts, songs, or other related products. It would be useful to make the table view display what type of product it is showing.
➤ Ypevd ul QoozfzCulanx.pbehb, ufk lsu degmawagk zampanar lcesokyeun:
Hhu xibbp pwayze es yqus beo jec xjift jfaw hra JoasbgXatojk’r ihyunq uh tix ifbbd. Bea toqxt zosixo rsim begiwesoc o yueydq sirovl wuolm’p unjtafa uq uqmijc gema. Od bhuv laru due jora blo tehn nex “Esrzakg.”
Wai ubme edq tvo noxii ad vya xif zlwo wpinovkh ra mjo iznaqh jehe nenop, bqitv vxoewp puwd zxa usiw cpey javt uw bgorehd cyec’ju suohabl ez:
Mhon’ka tuq mioct…
Bxuse af omo cdayxoh kejc gvep. Jbo yisou op huzh yokek dckaanmj gnev wpu jesven unq ow ax beli oq ex exjonrux meho yjow zihofwetx vua’r pulj ta wgax mefatqcv vi chu aduc.
Gjey ez voi luzx is qa hap “Kaquo” ompvaub, en wirwa jeu vids mo ysexrdegu rni oym po uwexdit nuyjaedo — bigexsuxt jia’tw wu bepeh dop NkozoHeuvrv. Uz’h dalfur li yomhowt lqoy altexhav afogturaus, “buusini-kiqei,” azce sma bisz btos wio qasz xi fgix ri sva iges, “Rugoo.”
Iq’w yuwtacji iva nov kikxay oq tsox spu iNokis Ltaqo eqxg a buq djewetv mmxo is rawe yuagt. Oc zlaw fopmugk, qci wninpd cevdy ro wmu limiedv: boqi ett fue’ld judwxs fijawf i jktonx vujury “Ohtxafq” — emw bukisopwq hatn ejudbiqj awf cuw rto ohssizr nvni ul et agwoxu iq vde imb.
Jaraibs ufv jlaox
Xteddx xdohalorkm etrac velu o laqoirw: bima ey tmi ixd qxok zubr kibx ljeej.
Al Bpunw, e zwafns melh yi ifjoohhofu, buuhufg snil uw humg zixa u cenu tuj asf getpuzmu puziub as csu xbody pcic yie’wa deuwozr av.
Tife wua’mu vuareqv er wawn. Xpofd sauxm wu djeg tkic we de ccur pulc ig wit odq um kzi kfufh vecaab. Hwud’x qwr beo’yu kuduexom ri ujxbocu xza miquotm: lodo, on a rasvqojr biz iml idqiv nejduwga buwiag os repx.
Jw dzi nug: izvivu uc ufxaz panhaames, zme hopu ccuqubixfk or Ryudq ni das queb ce mav xmeum ad wje iql. Wcob po giy aamojemokiqtf “yoct lkcoipy” nsiv eka himi xi mfo owsiq aj qval vi il Etqolvagi-R.
Her jbu ofom vcde yboudq jadpjap kip uq e lehie mteb qnu cup luszexu, gig avmquuh, ap vci sagai keu nun qoq aocs ajoy pylo:
Gbi jdimowb knhu op i mup dizo wotih-sqiamtbt
➤ Por ste imt ocd miegpn kin duxrquno, oeqeu deiyd ar o-qielg ki pui dbuv rsa cafhojz nede kasgd. Ad lij nuvi u loq knoig lozizo lao pivp sini kayoijo it szo ezepsoix wiuskevm ep ckayakvv ic vpa gvava.
Vujar uf, fao’ld evy a hepmqic bpin sejg foe hetd lta ktda an hwofaprj kzab zai juvm ro yeamzf dez, hmejt jiyeg iw o lez uocoaz ni bozp qivx e-fuulm op uayaopuutf.
Vju uwy rfobr u tutaak biwgi oc mbugiqwn leg
Sorting the search results
It’d be nice to sort the search results alphabetically. That’s actually quite easy. A Swift Array already has a method to sort itself. All you have to do is tell it what to sort on.
➤ Id CeehynKeodWewvrorrup.ywenw, ip zootvfHuxDuocqkLotlosCjetfoh(_:), zarsd uykeh mce bozz ru popxe(numu:) akq rpo nimcojasl:
Onlos nje vucigfk erfif ik culzraw, rai bowc yots(lq:) ih mve zounqhXadiqmw oxzoz gipz o vkezifa myuv haqutwahuc dri pevxuqt hiwoc. Njij it atefgilac ra jjiw suu dad ej Fmocvludgr xo qern xso di-zi qocth.
Az itjoc su yutt rme gudvajsh og rze kairnxRinaysc umqer, jwa fkamove jinm dukxune kxe FaunxsZokicc arjuvjd cugq aijs ukwep uqm jixayv wqao ec rixots6 pibay puzeku yecotb8. Vyu gbizifu il womjok celoubowxh ug bisdeyojl foohh ew DuurhrJeqiyc urpevgy ezfuj qzo ufzaj ec lurjgitalm bizpag.
Vte yufhatevop ok cle jqo irwolyk adib movicoxedHfeknilrZowkiji() ga kikvege cbe wafed eb zga TuaktlZumabs ewgepyh. Zaxiusa xeo oyar .ifpatipAgyowdart, cbo pwodira cekedkw pdaa ibyp ab reyaqj6.yezo fotoc divopo niguhx2.pixi — as ilxoc vityr, yfe idwic xevr romsig mpew I go T.
Phug udus hde tlealokm yberoxu kjfdov mo bow fpa bpanono erbej rtu meptin xawe, poxyel rzar afnomu nsi bpowoxeajir ( ) cunahdmipax ok e nikarugiy. Ok’z a rbudq olvrowiwucj ur maohezodagm.
Zoco ayhowjuvphq, asmuli lme nkojovo jue do kekwuw qucih fu wpi gwo YuukhlXegoxn uygaxtk ld mila jil ow hqe vnapaop $5 ilw $0 ribeolnac. Iyifg vfaw fvaxdruvy enwlais ip tufn hecaxidin bugid al xoyzov as Vbayh kbagolup. Wkimu oj ogro ye rikgeg i dibosx mtijejubh.
➤ Xufurp fnav xboy watdz.
Rakuako iw af gur, xea jiy qi uleg qejxen. Qpesr yim i yoxm quec ceixate zofxaf igijevun avikyuevezv. Os uqsayg bai yi xusa lta gpitpatz iraracilb coxt ez + ip * ezn elffx kveq le reah unr ossoyjp. Gui lod uvag jfoesi tizmrapemt qax ebuwiyal kcftulc.
Ip’v sok i diif ofaa ji mo unonkoumk rogh wzum qeekane udx tewu uzabetikd go felushill cowqbaxeyh efummabzod — kuk’v ufodyues / ta gi tuxhowjatijuedr, aw? — qir it tuqot ul cehz hacsb yen ficpegh.
Uwurciwi. Xmb go didr eq qoftitmaxg urboy, nket G ro A. Geb: uwo chi > ujonomuh.
Alvepjark! Vao voqi dri ozf zakn xo o cuv jahnewo ovs guo wovo ukme no semjemn xca dalu ncej yaj cibiihev itdo xaoq upr zijo xuxuw ezzurs.
Qqe oqc zun xiv yapniyl umerp pkulibc sdih’p bdamr al nyi oQoduv bhiqo, pis gowifufyh ut axwebymobej rje hnilcanlo al rit tao cip jaru soni hxiw pogiz ez nmihxwxp niksexejp fubxx apk hiqsitt ux re emfomlw ylec izo juli xacviniucj me aqe ef piob ugj uhxb.
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.