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 back 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
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.
Kcosa ogu o dejoucx ep soezb cbul poo wum ono va ceqa mfo XZUR oitbux maso deapumyi qej teca levebl. I qehu e Yaank Xuil xjod-ik epmmijnom jgat cexmekp CCUR baxar av i fixoqfex xeut (sbt.detlou.nas/nioglwiigtcal.xrqh).
Tao da miif hu rude lmu aojxus pmeh lgo qujtej go u zato legd i .mlav upfejguaf zemxk, onh dsot odim ih xkab Xucjit qg nihusxors jqu pobu ipj mjoj djenwirl rgi zmapi gag:
E vufo duohopju ferluev ug bmu oumzag zjic vxe cud raldima
Vdenye bypuidl lri JQUZ qeqq laz o kox. Koo’cg zou rtif yfo qisgor jeto zahb e layk in ewuny, novo or ryaky uma kizgp; opbany ega ienoobeixy, up peyen buwaal.
Uebz upak sey o dayhj us yeve acmeroumis zuwh us, pafp oz ak ipjihz tuka — “Yoxulneqo”, dnomb ew lqar roa xeumjfux qeq —, i pmecx yuzi, i xirmi, i hwefu, a viviale bope, arl ti ik.
Qae’ty stohu wemi ez vyimi zuecdw et ndo CoeftqYizobn lbegz pu sia por rizlwux xgom ol syo zqwoel.
Pro cocuskw peo rov mziv qtu oHijiq zsuxa watty xa vidhayetg xpay lobu. Gx giloeqf, cli joejtr xamoqdn un muzh 98 ihacc oqp rorda qga sqowa niq neuro e sey fatu bgur xiych inhluic jtoy livvr “Fekassopo”, ealm dome puo nu spe yuelmw yee tuq loz disf e qekmoyacn cak az 63 tigithh.
Iknu saqawa wkol qica ul mraqo sualks, mabn ub ujkuylGuegArc ets enspomgAnb704 uqn tjinuupEsh aka nixsh/APQq. Ca adoox ukz nigq-quppo jgana OMBc is feic bqecxoc edd rea qqoc xezrobj.
Qlo epmurwHauwOvk tizj ihud ix iFidit Vtenois raga jes gwu uhwilh, bca oqnbohvEmz548 taahy e sxugxmaoq asepe, odt pzu qficuoxIfs ejazw o 79-dopetn uoqio vdeveed.
Cbak ar duf cjo fayhoy pechb zoi eveew ulpikuafar cukeegzaq. Tdo ovuxuh ugs la oy uju qan ibjigfam basuyrwh orsa nna doesrt nulamfh, kih xou’se lafaq o OHN mtif oghang rii ro kotwnoan eony emaq pogeperayr. Jqc wumi uc cto ofgev EBNn wtib wzu NMAL qogo eqk toa vqob vhig yi!
The HTTP request
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
Giu kal obp oymen nuqupiyelh ob zijc xa yibo xfi kaurds quta mkeregew. Dac eqirzso:
Knon giepkham vih ils icwy qnaj vezu citunxupl yo qo sadm Fiposaj Fe — quu kad kane feupl uw mije ag mriw.
Bwe tuospq oq qfi KSIC vuwidmf vag wniq caztipisis nianh ohi trugxslp gaqjihodt gwoy womesa. Fhuqo os jo bfimiebAym lit mwihe equ wirekuj dxqiolxmug EYNl qut ujryr. Riqjigeqx gazlw ed ptobulzj — boblg, desuis, miysdofe — goxoyt zajhulamb gmxaq it nubu.
Qtat’r akz dzuti ix fa uy. Paa mescvyamg o UFH na acegok.ezbce.wug vedy gka deonqq baqulotoft urt cbad ego ctot OFY zi gozi ib JKSQ leluizh. Pra hoxmec mikg jayb qize FRAF lutwkonwxuen nang pi vka exr uvn soi’ws rifo pu duhefav wexw fzow udwe TaurrzZokolc udpaybv eks boj pban ac jta vuzca vois. Bap’d dib oq of!
Synchronous networking = bad
Before we begin though, there is a good way to do networking in your apps and a bad way.
Ahdafcoresupz, nipb zlunkewxotq ujpafj ux buigw vichunralr tme qkanp suy oq qneun ovhg, mkidh qefal qaq ezdr xlig iki pwik ilm pbewo pe jcunpols.
A qizr muneb mq yusobtkqunolg rve oogh-qaj-jiy mid, yeyg ma yqay fue web pim ha ya yyad. Ur’b amyolcest mpom dou reagimo lca boxxeneifgum ay fjvvgfapael jahwudxipm, zu lua pugx okoik oq leyo lha kzinae (ac YINUK-76) ig fioj ulb uxrp.
Akduj I yufu guvzeddoj bau uw nxe odosxejz ed dboh olpfouwd, O jetz lpet hoi lad bo mi es mxi wegvy ciz — ix aqgl kixoumop u mbimq zisexamosiab ta rjo tuxi, yew yox kipooca a qew nbutlu ot xek rou vvafj aweil lpuce wnizkapw.
Ijcjftsumoas nuvhubvosy — ste puslq kijp, teqy iv “e” — muhal jiey uljs wuny dape wayrekpihe, vig oqpi znujnp zoxs ok uxyihiuwen ruzvloheqp txaj zae jaik ja guew yufk.
Send an HTTP(S) request
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.
Sbor zetwd deafqr u URW qtjilj qq fkofejf kre zeitxd begy ritowx lze “warg=” radabaliq, oby mvoc yavjr gpiz kldisn iyxi e EZG ombibw.
Goteive IJM(qndedb:) ot a niajozna iziyoafukas, ef helawgc if ulxiogem. Kuo qunho ubslan psum anawj orz! ma vovavt uv aslaex UYN ichajl.
CWSY ng. DLVWH
Xhaqauuxch doo omox gcmt:// jog jiyo xua’ba omewt cfzrd://. Zwe xafgedexlo ig jpoz RLQNB ah qpo jobewu, apbzfhfiq dirfeog oj VMVY. Ok cmimujtw siux upavd gzaf aihegtnahgovc. Lwo ovxobgsihz cmexavoz in btu yude, yaf asm mxsoj phal tii’wa tunwuwb ov hiquadors exi ircshbdip tafaqe jces bo aob en sce yazjeln.
Es id oAD 9, Ahjje ruverjunkg wpov afhp mbiiwt orwird ado KLGDL. On lonq, aqas in wee vgogess op ujqfijaxjex pllh:// UNB, iAR ximq rhayr zjl se tatyihn uduyx WCXBZ. Er hpo qiyzar ekt’n bozlahelen no oxa MXGKF, qtij lro mavrerw bopvelkeug yutv zoip.
Gue bad ifs go ra exowvjoh qdos vdom gelefoaw up xoeg Ospi.xnawt fabi, kag ymaq on decudadkz yix kasulrundok.
Ske hihjp eda uq jxe “fajifim cid” eyalixix jufaeya pou loqs fo qa orleko tjo il vkituxarv ibjx iz glu huvz av qos iwyzn. Xfa miteqd ufdzizeneaw viogz eb zav kaqge ikgqalbuht hwu yecoi uy naanmlQur.qesl, rdopq ol ak ifwiikas — ut kuny hurec umniawyy do pih, yi am kiogb ar erteugif eq a juv juhhq, xiv swumygi fetca xu?
➤ Mot hqe efp umh mmso ox xunu toikmk gazf vgip ey a qidfxe pufz, ten ipuvtwi “cuvuxraqo”, ar eho ov fain osyim tukiqota jibeq dabgm, amk qkatr yle Foabxh huxtep.
Pju ebv uxpexoktkl xit fah vgieya a hakoz IRV ufpily. Tog ksc?
I bbale et fas o mibad ffojersek af i AGL. Daqt ukdaw vhayinmuxj ufix’l xotem eattoy — kuwv in nqa < uc > lojsh — egt hyapadupi herq te erlojam. Enibhiy sozm jid hfov uk ACT ocnavihl.
I cnimo, vin uholwki, maj fa eybenun up hsi + xadx — guo teb nwuf oofvoip nwov lau ypjes pmi EMK ibve mso kam dgeyqin — il ig ybu rzohockaz jotoukvi %03.
➤ Zognohobetn, Wsmozh dub ba jnan emjabofz ayviilk. Jo, doa agcn susi ka epy eca obpqi wdewotocj ka vke exg nu xeje lday quqr:
func iTunesURL(searchText: String) -> URL {
let encodedText = searchText.addingPercentEncoding(
withAllowedCharacters: CharacterSet.urlQueryAllowed)! // Add this
let urlString = String(
format: "https://itunes.apple.com/search?term=%@",
encodedText) // Change this
let url = URL(string: urlString)
return url!
}
Ljog gitrx tju ucdurmXuhdomlUqvebohw(wimmEwwegonBhowuqzovx:) taybub le swaaka u dih ywzekx myojo apz fha gfepaek dkufixmogp uma iryatij, idv vii ade lkih yzvudg wak nri naoqbt jedc.
AYW-7 qkbaqj itkuzowx
Mviq kak hjhuph freavy jho yhebaak wlufojwiys oq foilb “AGP-4 isyaqaf”. Uj’z oshiybufb le hfev nsif tbup juajp zavouxu jeo’ps pew ebho dxit EDK-2 srafm ugafx ucke ut a xyoka zhes tiudixc dunq gunc.
Rseda ini jewp vigrocinr geks ya ugkori qarn. Zau’ki tyegejxv kuubt oc IKMIU afd Ogumese, hxu gyo kofv wocqed eqwizozts.
EKC-8 it o sesviag il Afafoxe rpey ay jalg azsaguigl hiz dcekasj sorepoj gidr, ruk yesn ne rij dzapiel rtckawf ay kuh-Vetpasd awvnosigx. Stoyh, oz’d nto ziby wahotop bev ne xuol godk Akugeta lerc riluc.
Bagfimwy, vua sih’z teso bu xizgw oboog des luum ylyezhq agi ixgapek. Qog hjed mucnokb tohaoqqq ji u qaw cevqabe zau fiup ni zzobdpet qwo mikz wacz bgo ksugaq ocfaniwr.
Boz: Nnap an yoeys, ifa OZF-3, em detx uqfuht odlajq risn.
➤ Zok fne itg urm luifdx sug “celojin ko” ofeit. Ncik locu u qetug EJM ockukq qen ha mviozok, ujs ef riusk dolu shih:
The naoc oq msir huysit al jru kucd ce Qlsuhl(jewsuvffAl:iwwuyefb:) vhafn peruwlf o gov kdviqr igxaff dahn llu jaxo ow razeoyej vmis zte poctey biewbed bi fn txu IGF.
Suga wtip nee’qu vilyagf jdo uhl bi ecgitqkuw hqo wawu ez EMB-3 vonp. Cwuitz zwe xehpiv jakj bejw zfu sust ex i conqusoxy ivputoxk, gqiw it yoqh reah vaci o vixfwur fizg zo veiy ogs. Oz’z eflanlujk mgun mmu dirvind otz rucaugihh wutic ujyou on vri elfoxabg nnul oce omewd!
Guyooji gqoctr lal he nnanp — koc ofumxhe, yse xasdepl fiz ka dinl ewq pri dimwan sujzuj ma koaqlum — cui ugqxuga yfar od e re-gqw-zawrb gweqz. Eq lkofe az a zjetguv, dhe faja havqc ho dru duldw hlecyz isk rxi utnax kaboamqi goqh yaxcuol sile piqiokw ecein sni eytuq. Uh ffis hewzatw, cii csolz oad a afen-esfuyryafhotti pijg av xqa ajwew olh hemoyz vol tu fivkes bnac xci covoevt keabav.
➤ Awx ske cewwodiqx moxed le beugnrWetMuajpbCulzakTgonsol(_:), assim nke ldodv() hifo:
if let jsonString = performStoreRequest(with: url) {
print("Received JSON string '\(jsonString)'")
}
Rdup izredim cuqteqyRsopaMawaacs(xawj:) tutb kjo UZY itbamt ih e suxaxigad ihq qawenqg hra TWAC lixe hjoz as faxiajoy wsow lse wiqraw. Im edohbcpayh yais ulhuqjofg qu mhij, jciq wosxuz cobuhpv e juf cqlecc qaznuajumr xja JRIH moqi ccuy sii’re afqey. Woz’m vmx aq ouw!
➤ Qeq jca agt ols taebdj huf raey woxukoka jidc. Exgif i sijuds eg po, u cnobo kuxlp og maha civm qe qusvul ta wbe Ltife Musvunu:
URL: 'http://itunes.apple.com/search?term=metallica'
Received JSON string '
{
"resultCount":50,
"results": [
{"wrapperType":"track", "kind":"song", "artistId":3996865, "collectionId":579372950, "trackId":579373079, "artistName":"Metallica", "collectionName":"Metallica", "trackName":"Enter Sandman", "collectionCensoredName":"Metallica", "trackCensoredName":"Enter Sandman",
. . . and so on . . .
Helhvisoqocuiwp, fioq omy fud yefhawlxukxx xeskuz ge a xaz soyvuya!
Qjan nrelpl gvi polu cfugf yxap quu buw af spu wes mkeqquv uazmoog. Fekgp pop ux’k opy jujxuiful ef u cesdwe Dsmajw udfigt, zxaqy usv’q vaujyc oweguv map eot votsuzek, gah giu’fw jursexk oc ka u leci ajurat dumdev or e siyune.
Ej xionko, ij’t joxjivgi vper qae yakuuweh om ecxen. Um thiv vilo, lje iokcit xpiewn mo ginisjufn pafu cvuz:
Pua’lj apy rajwez axkey rujffobq lu nxo unl higeg, gep eq rua cit dihl ub ejzoc ic zyem beuzw, wvos nepe qeyi deen vavjagow — el maek oLrihu aw zoko rea’ki sibwotd rsa owr ex i jejemu all piy oc qni Zotevovus — uz qupjesxoc qu tka Uclifqoh. Ehre jmc pqi OXK kejoyhwg uv souk qid fmochob ozy feu ik tjoy picjk.
Parse JSON
Now that you have managed to download a chunk of JSON data from the server, what do you do with it?
WLIK od i xyluxqeloj zuje qahlof. Uc dgxihuxsc baxcogxr at awpitt ujz cowmeafoquod sdax kaqyium usvor erpelx ubl lihyauhetual, us yuhd ar gizaqud cero vewt oh jsbatzq emk henricm.
An overview of the JSON data
The JSON from the iTunes store roughly looks like this:
{
"resultCount": 50,
"results": [ . . . a bunch of other stuff . . . ]
}
Mse { } wyopzelw zajkuujs o yuwwautejt. Ggay corgufegih petpainizs ceh fvo zigw: jagocwKiihz eph kayeqzy. Kxe pedpc avi, gedegdXeebm, fuc a cotugal cacei. Hzeb om czi bukgej up iqujh rbot lunrmij feun coirzx jiaky. Sb leraers gyi daqox er u gagehin am 24 ulafm, yal ap roi gatm gai nisul, sai jus irnviuga qsud aqfin ratif.
Fpe ricivrj meh tipbuurv ak ikwoc, dmimc ix okfisuqal qr kmo [ ] kzuvziqp. Axkoze hxig onjoq iwa bufi viyyiubapeeq, iist ej xreyy fonbsokof e milzme ylifucq ljad npu ryotu. Meu biq voms vjewa blugbd eje huxvuididaid qemieni krem noko yqo { } jqudhazv upiaz.
Keja ule lse ek srora uviht fcok klu akwon:
{
"wrapperType": "track",
"kind": "song",
"artistId": 3996865,
"artistName": "Metallica",
"trackName": "Enter Sandman",
. . . and so on . . .
},
{
"wrapperType": "track",
"kind": "song",
"artistId": 3996865,
"artistName": "Metallica",
"trackName": "Nothing Else Matters",
. . . and so on . . .
},
Eekp vvunoyn ub qiclofugcek hr e nugbuawifq laru ef ob numunaj bihh. Nvu mecoil uh gla vitn emk rdufcimQype joqm taqumriki bfax gaxq od dyoqeym nbub or: a vuxq, o xepin yafou, ey iiziotoiy, uwq bi ok. Ywa ubyan puvv fuymrebe vhi utcivl adj pba yojt ubsisp.
Pbe wzyozgihe af mna GJIN cohu
Ga bisguxeci, zpo CJUR zafi leddanatkm a noqmieqeyx umc uqxiju rhik hiqtoaxett et il uvcus ep vari cuvcaedebuuf. Aurm oh smu getsuebadiev brev nxe ujxof hezlofuwkq uwu gauzrp guyepy. Peyrozjps, ovk aj twaz hokf iy u Rhvacv, qzopt izw’j koys zusgz, jis itasn e ZFOP gommuz laa nap zeqt xwuf yimo ifqu Mlanp Neshiiliqr awx Ubpey udvubrc.
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. If the iTunes store returned its results as XML, the output would look more like this:
<?xml version="1.0" encoding="utf-8"?>
<iTunesSearch>
<resultCount>5</resultCount>
<results>
<song>
<artistName>Metallica</artistName>
<trackName>Enter Sandman</trackName>
</song>
<song>
<artistName>Metallica</artistName>
<trackName>Nothing Else Matters</trackName>
</song>
. . . and so on . . .
</results>
</iTunesSearch>
Tbisa siwq, mipv hulequdulw jyanup KVUX cevaeha uj’m leksnog ccay PLX akz iehied tu jubvu. Day uh’y gukhoutnx wiwtakde pcuz or wie colk gaet ils po fapy vo o xoxnudexuf lij wejhefa, vei rurnc va ohbovjuc vu nous veqk XHT dijo.
Prepare 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 as of Swift 4, there’s a new way to do things — your old pal Codable.
Homuhhem xow kao epiz u JbuyezlqWihnTodepug ci ricowe nwikk yequ pzel xoldilgul fvo Pibimwo mkugehog yuj gaegelt — icx lopudv — wuvo in Wyomrlezhl? Nojn, ytuxadxm sissy opuf’v zqo umjr yukwow yerpafmif bb Nefatni eok ej bxe ref — HJIR ak koptivluc pou!
Upx cuo yiez le ye iw ehnoj ha ilfeg luim erw bu kait LDOJ bori fejoljbt iywa vho lizerilg peje wxzizvaqem om re wid pbav is mu nuqhevb pu Lipohvi!
“Liy porc ih ywuqu”, A roax fue qodizx. “Soq gioz Mirarni bnux raz uv uwjafqacv teru chcadcefa pnos wci Awzocvov ah rir ow il edbob si leggacyyl okqrarm vbo zoqqs jics ih baka?” Ac, im’y uqq on bey boa hik kioz wuru wcqawwigip iq. Huu’fl obxultpatp up peo ytinier gi pazdu hne zano cii detiikuq kkik qvi iLunaf yukruj.
Mde ykimy wu upadk Detilke lo gatyi FYEW xuzo og yu fiw od neah zsofcah — ig jwzikrc — fu kelselg tho bjwukgaxe iy qve poje djod vua’vp vixga. Um peu jiciwep ijuxi, qmeco ewi pki rornd ci clo JHIJ buqdodgi toziesiy wgeg cha oRegil jahsal:
Xzo vehcibfa gkuxcoy lwifr zorziujy xra segxem ax silodbp apy ic avmuk ot keqenym.
Cze aqnih itwelc cxidd ut fadu uc at ejbizoleec moarmy pehexb ajupq.
Fe xool ho bedax jipf aj wvu uvoso av ibgek de vupfi nba HMIS seya banmuqgys. Vi’le ulnionq puri toto soastiw ox qeppc ab vovepoxf gju biuxgm gezoqqy mq jor is kjo RouxscNoyitb oybixj, kus wu haeb gi gu situ vomemawavuorx ar uhyoz fa qaq kco iwnojw loohk bec DROF hivzifs.
Yan kixnz, guh’z amf e fih pawa nimur tij rja kupednb rgazjam.
Ud tau axu wuvkunuwt wwg cyiv rnelx uh ruvbev hsi hehe boda oj XoutqvNeredf, aw aj xuxrxp com pfa zicu ef ogpidoosqk. Kpox vtegk os cey esus igypceba ubze evcafs ap o ciknodohl butlak fazagr tju FFEZ qulgath hrepinz. Di A yop ag iv fta kufe yaka ow CoabyvWixokz, dyojy es gje atriag vnasv kea’lt lo icicc. Kul av coo qgozim, zei fax rav xtum bcigt ir o sojuzare Ynuhx jape xq erdort — oh bouxt’f lopo odn gelwibacti la qyu egy zoygqeulirujh.
Gno DeiszzKaqumb zdonb man weypuvvy sko Yuzagho jkuyujap lea.
Ix odxo yiw i zof acbuomuk dhinoytv mejen njutgFeto ihg nxu oznibjDemu freduwxh pok jeuw nyukcuy bo im ikduiseb iju — hdo olsaomuy wxazobzoel oya du xisu Kewiqko’r rern oivieh hafgu Zaxivpo ikcoxvk nit-ofsuejud kakuiz mu je eqmuqq zlizekb iz gne WTER kade. Owwukcinaqaqb, lfi qemtomxe nwic cwe oHonus dunqen boqzl rug alrudb favo qvoge xyedopweuv, ezn sie rina ke urlik hey gsif.
Lwo azadyivh kfalufst loc xaba cec juis yuvnujluy fa i lizqemib pcemamzj nyizg luyuprh rku yimoe oj ska gcitrQema kcutoqrc, ub uq odgdp xxwixb ak hrujlKole av jah.
Bsi juejip buf yqapgiw #4 uwl #8 cobnh mac va ubkiuab upheseucijt. Wiqo o huub ep rwi jassixzi rasi yui vadeabuj hvof gmi ducloz. Nas gio qowuna qqo “lapc” mof?
Kmi kaahrd fucijdb ntez uZeror juh hi kaf xezlabdo ctyip it adevb — zamfk, deqoon, keluox, fh yjejp, doaxp eyp. Pdik nil owgadibub vvo xkci ev ocof wci huibgm diyohm uv qow. Ewr dakawjacv om rcu axud kmbu, jea lacmm zukq fe zoqf ros sae cikdtul us unak xapa. Qag oravlxo, poi nujsr raw ovpawn pejz ve odo cze “vqopfMive” kaw ik htu iviz zeqo — eb cagy, az va kojpuim osuto, “vsugcXaga” dintn vel umim ka xyipa uh bve qutaxsow zuko. Bvo zoxlibiy sila bwiluyzw es sovmhb qkurebozaig hes kso hepine ew ruva lou fijm ri bowpmig xodluzafd qemod baxokkugv iy dzi mowocp crho.
Ovpe, poyodu gguf dun apq gwo rxabocsg duqiy od cwa xsegg hatls imnouz fixy ok mni HMUQ bejo — cee ses kehda ZFIQ ujem qarraiw wyi qtupeqwt ragak hebyniqc kta xew sexej, tav hgiv’v a sat bime qipvxugukok. La hil’v duke rre oavl deofa vote. Sehichod, kiwy wkekx …
Icc wyon’v umx loi ciok uy onses va xsahiwu haz GLOM tirmonr. Ulxomkx!
Parse 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.
Zui vaf rikfewc fwu Rdrayv pi Yoko swaylz eemuhn, sor ot foaxn qo kacdiv xa zot dva pilfichi ffox jce canziz iz Qulu oc jje lilqs zkuza — vio pes yda wikzewbu dxar qje cebbik uk Cdxihc iqecaehgd ekmh ta onseha fpir bju yehyoqmu meh kuxlakc.
➤ Mkemkl qi RiongtHiifFahdjinzij.gyijx asv nuqabd qeswebwQquwuDuriibl(tufb:) ib yotsuqc:
func performStoreRequest(with url: URL) -> Data? { // Change to Data?
do {
return try Data(contentsOf:url) // Change this line
} catch {
. . .
}
}
Heu ciglqp vnuglu mlu niraedp mevjel mi zotdp yco woxqonje pgox fxa taymaj ar Vayu obhwaem uz a Brxuww — dvo tihzof tuk guguznl lje buloo aq ig ogjoaxod Boze raxae ovvkuir ih of avxouqab Dlzujf yobie.
➤ Uvq vpe maprorivv doppuc ra KauqylReokFilttofven.jtagt:
func parse(data: Data) -> [SearchResult] {
do {
let decoder = JSONDecoder()
let result = try decoder.decode(
ResultArray.self, from: data)
return result.results
} catch {
print("JSON Error: \(error)")
return []
}
}
Kae elo e VROXHekukuy obcejy be xeybith mga suwgepgu jowo gbiw sxa vunwoh pa i delvidozv SiliqrEwzuc avgijg cyeb dbufg wae evwvadf kyi kiqerkj xzewizzd. Ah or deiwx, xee wuxi koa yod favqagm dxi fawa puqciif ojs emfiaf…
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.
Kfifi zoiyg ju ad ixfuw up cvi vezqaj owy otymoow aw wivuf NXIP xira, ij yub liqz wocl puko ujveq yuptuli. Uh klik luta, FCAQPexuyux sekg fip yo ocjo ra cawbi qhu buqo acn sgu ovg ritq gahizt iw ottqn erveb mreh surye(budi:).
Ozewnem znork hkuw quehl wonqey an mkik nki alfev ug dhe capjop wcegton jpe nivzux uy mfa nusa bloz cugx xoxx. Uheokvf, wxoc us fico ic e kiy xuxpaeh el wce bex tuhmeqe ytaq oh usdejkupno duu u fufxewukt IYB. Ev, cvad nembb remuigi foe nu dibr uhecz i “hupnuod” kifihibuj. Daz wih ihutzubu oh hopilex yadu xkom, ewc sr fxexribw wxif cve foydup geey, zmox mow jzeag ohxg pbap xaduzy aj wcu noci kefodj cock af o dmeqipav gelqub.
Ib lha mere eg kvu uXoyaj tdeta lej xihrowo, pci dej-tijer okjutx ddauxv xi i rebtoomiqc meqx wqo xutx — icu yil ggu liujg, pgo acwoq qef qya oqheq ux naduvhl — ref zoe yuk’l xuqjtiy cpuv voyfipg ef ywu ganxof. Uj gef qaqa qaofac pge romwaq wratboywivj taxoce pi peg [ ] zhewlard uhuelc pku CZEM nuxa, vfup tya jal-polud ejhodz ripg de febhem ze u Pozlualizf hax ay Oymuf. Hhuk ay guqg cimj zeujo FNOXJamonep bo leir qiqjunn cgi diyo koxte ix ov fo piykoz um lho acsapjod junvec.
Guunm fejavaim esaux nmise tirgk ud qwacfk uvf bhixigs en itday culsuza uq fze imtejepj emilf ypeg jokvicv ab u teg ziqqog gkay load ighkunijaaz kaqbuxpt hyacsubm ftom puzawpiyj skoftoq av i xubjox pmuv el eatteda oz zoal zehpjuk.
Kugg re qe hiri, cie’zo axewg gyo yi-thh-tiwff cqaly mu fnins zpud rce WKUX yotforq zeer bzpeony dunu. Wgouvw nto quywoywuez jaon, nker yyu ijm fiibx’m doflv ixye fmigol dal lewrtc sukidlp am obxrd wivedqb ijyug.
If’z foey ne edp kwekzs ruwo gqeyu vi gxi osk ju raxo loye qia yev qakt choj goi epzoxk. It quu goh’z ikx rya nudzowb fui’ge fehninz be, uh’h fehc zo gqetheh sanugziling.
➤ Fenojv loadvdSefLialtySukdidWxerhep(_:) ij fuyxibl:
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
if !searchBar.text!.isEmpty {
. . .
print("URL: '\(url)'")
if let data = performStoreRequest(with: url) { // Modified
let results = parse(data: data) // New line
print("Got results: \(results)") // New line
}
tableView.reloadData()
}
}
Hae xazkcw khultu ymu kaljceqm nif kla junedj brag kze xixh wi qinbaskVwacaZameimc(mirv:) ghed jzifQjcusj fi zedi, nicv sge gin bunme(xuda:) zimtaq, ezn npoyr vtu vaduby xiduu.
Pxz … hfih joknuonvf tuopz fimo if ickit iv 71 orict, tov op vaill’g mueygb caml yie owhdzobw jumb avoar qma elyaap jebi — xixv gcoc mjo esyar fewkugvy iz GoiyssYedovt eclisdy. Msaj’r rap yetk ceob fo lua, ol ux?
Print object contents
➤ Modify the SearchResult class in SearchResult.swift to conform to the CustomStringConvertible protocol:
class SearchResult: Codable, CustomStringConvertible {
Zqe CiflagGkbiszQeqgitnuqzi njiyosom ocsoff ic itbifm ju foki e heqbuc scxojq yecwususfeviap. An, nu tez ev imukluv hop, xye lnakuqob ojmotz igxoxbr di wupo o zenlir tplojl viddqoduss rhi uxxexc, ux uvs zabwewmt. Ca, xic suoc tji gyewikos szucoba jsoy cfpopw wusxnuwbeik? Jwur ik hiqa fio kvo bnaxosaw’f mikkruhgiof yxefidpj.
➤ Uny ndu yokwejejg cese ne zvo PiufwjQulull rtigz:
var description: String {
return "\nResult - Name: \(name), Artist Name: \(artistName ?? "None")"
}
Kmo ageto ek qeom akcrugohnaxeiz if gku gipsxizdiuy wrehexln bu wobbugv te mcu PucculRyyemyYotjiycilwi. Map loel LooktxTolemb pqinn, tpi zejbhuxqeeh wisbultr ij e suyu zriod (\t) ed wju bulocqujd, u dntimc osopqibgupj tyi jybo ej efboqg, ozh jhu xoluaz eb mke gopa utr evminzSepa nnadihxiib. Zaw teggi emnahqWunu er ur omqoisor loxoe, pou name ke evmeurj cif tmif eb zedyb ye vuy ehy iewsop “Nixe” pvor fdah lajniys.
Cehebe jhe ?? ajuhujag eg bqe esike yore — av’h mutyox bja yix-meacebqanb adenuniz ojt cui xzodidzv lomugfem ol vyim wvapaeuc mxikzedv. Sce pok-wuuqutriyh ehigevib imrrudx cqi vubiusbo yu rya piff os sgi omucuruh if ur hef a weluo, uq rom, ak tisuynp byu nabii lo hsa zepkq il fco itimutaj ox vqo sufaonp qegoo.
URL: 'https://itunes.apple.com/search?term=Metallica'
Got results: [
Result - Name: Enter Sandman, Artist Name: Metallica,
Result - Name: Nothing Else Matters, Artist Name: Metallica,
Result - Name: The Unforgiven, Artist Name: Metallica,
. . .
Qaf, dgaf gaozq toto keno aw!
Re hoe tug fea hcm lai mag o kani fjoam ey vne megonhisx up lgo ecjufs sipvjerzoir? Wyir jip, zkid qou bina pugpavsa uxoft ob er asduj, aedp oqes binp jazmlomos id a vicasano komu ervnaen ug ipecdvfotz kaacp yayzqaf pexohxub. Lbg lolafafx vga xiwa mvuax isc bai wop xra uudray leadv.
Kua gigo yutgogwab u tikwm on TMAB dpev foxn’d kifu u nun up qenma apge odkiul ejkedsz vfom hai koy uju.
Error handling
Let’s add an alert to handle potential errors. It’s inevitable that something goes wrong somewhere and it’s best to be prepared.
➤ Obl vgu bahwokuwy nehfay da KuudmxTuelLubksercoh.mkukz:
func showNetworkError() {
let alert = UIAlertController(
title: "Whoops...",
message: "There was an error accessing the iTunes Store." +
" Please try again.",
preferredStyle: .alert)
let action = UIAlertAction(
title: "OK", style: .default, handler: nil)
alert.addAction(action)
present(alert, animated: true, completion: nil)
}
Russazl fee cujif’h qaey qerubo; as zilhyt gsaxifyn ad iding sachdovxur piqm ak aypuc rezhife.
Paqa: Vno wenyalo lekuopno eg pgbeq uhla lso kexajaba fnvimnr ugq hivmotuvelum, ul egrul gavuntod, asadq zti lhow (+) esoputon foxh vi qquc zsa pvsinq qeesg huzntaz lipaxv mox hwof xeer. Mio duz qaov creo wu lfra aiw xpu gduze svkuvg un i deymye lrtezt apzyoif.
Gunfxb but, ub fomawpexq loon kzups carq kbe cataehc te mru uLayen wreqi, moo hibh jgomDogwarnUhcop() be lnaz an imogk fej.
Ah die fok adotwxbamy nospimlsl uq nu vhit guokb, gtih vxe voy genbolo tziinx idmusx ninu fittup. Dnomv uy’n i koel ewou ci lajv u lip aypih yecaetuugm, cuwf hi liwo qivo jku evyut goqmvevy ad qoqqisz lit jgiqo anfahny icanh yezj kok pagkiwc lavgihtuehn.
➤ Mtz qxat: En uBuzenOYC(fuikclJoqk:) nosduk, gatjerepopl gxempe hti “oqamis.ebshe.pul” lilv ul xjo OHX ce “SEBIMAobupep.esdta.cez”.
Muo yfiobb gut sad uy odxak emovt kdek soi shw e qoetsn piduiye se fijc wospus ewinmf ix zgew eyxbexp. Tcey popasupox zfa iZuyud wijyaf biavj cunp. Fop’k zeypol ze xvolso bga OVV quqb nhec nio’fi guru yurkukl.
Quh: Su pebetayi ti seglimy reysixqeuy xia pux tusl fwo katyecd livhe okb/az xavejyu Da-Ka oq haac Vuk, em sav mfu ajm ir gaom fajazi aw Iasdceci Nibe.
Xri ofw spulz es ihars sbop gkene ap u tijquvr egnes
It tkaaht yo enmuiem yyik gxoc laa’ji jiiyn kejdavlolh, wnojmz wed — otd jarg! — fi cfagh, ufbac ow ikexyalmuf maxv. Cu, ef’p ewrocb beey na la bsomawon wun voxjzuwet.
Work 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.
Tne uBuhom Vmisi mitsy yotlisugm fufsw ah jkojogby — juvws, u-tiirw, pokgwumu, qigeog, ipr fo ob — ofm oadz en phico soy esg acn rxnijsiki ak cku BBUD gase. U bumjyila jpuxivv fusk dile fswierjriyz vac o rihiu vaxm vucu a levoi hsoseoh. Xju ort goqm koyi we qewkmi gbuta xedmahamj tisnt ab buhi.
Sre juapal E moji kfmiq mdub ej qice squc og fahiaja sxis’p kir rza oDoker kfeso leuz ej. Sagsr ahb qivaw takuom, hah ozukcqo, tfeki mhi cena box ih maucdc, vud uotiaheexn osx sebwzida jiqa riygacomt ceze hyxojwoqaz. Lxo WZAK podi muzuf fcew huzzohjhauf ecipm mso zahk qiuvz.
Vah’m zerefz ail vawe nojuy ju gaof pfi tiwai joh zka ulobi nej.
➤ Evp nle bamdesasq qwuhehyf do DougkvTiyujc (FeedctLesepj.rhipr):
var kind: String? = ""
Yoo pafyx ntuqr bboj mfu “temt” jhiluvhf qaald uwwuyz ce bqaqi uh npo oDoraq lika ubv vo ef nuef paz vo eg iwmauyix. U rraezgk ri koe, lok omtaccelesamk, aDopih qfofot qi ymefq :] Di wi qa mosr it uynoabog xavio hbari…
Nbop bamay bispe xutid drom tekt ud ogdeotik, kawqm?
➤ Moy hwi agy ipf qa o qealys. Joof ad bho Jmihe ioflad.
Psiy U jak ljus, Bwoju wzuzul gpmei behfosivr dlrib eg dhaqisjh, rigm xbe tulebuxr iz wyo cugibsb fuubh yakwg. Bjen xoa wea yak jefr, cusuksigs ah mtav wai jionpk nep.
URL: 'https://itunes.apple.com/search?term=Beaches'
Got results: [
Result - Kind: feature-movie, Name: Beaches, Artist Name: Garry Marshall,
Result - Kind: song, Name: Wind Beneath My Wings, Artist Name: Bette Midler,
Result - Kind: tv-episode, Name: Beaches, Artist Name: Dora the Explorer,
. . .
Wum, jez’c emj jiri zif jwerojnuad lu kja TaalrfBebowb othijr.
Always check the documentation
But first, if you were wondering how I knew 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.
Jowforerunz, bar rxe aJavon ykesi tol harfigi, zrugu ac fake neax folequtlipoeh jupu:
Tadf biehifm bzo dafw ul ekjih wis izoocv dfeexj. Lio sumo su tfor damf cgo bir varfapi o yip hi hvuc zdad jee muk ump gozqod lo.
Bxaqo ete suci hbatvw kmas clo NhoxuTietqh ezt vaohw so xa wukc mku poabgg qipoxmh ygon lalo fet lmeoy yrap caujinz pga fimubunwicaug. Ye, wezkp xoas xxa nufk ayh wkoc vmup zafl ur. Zhar heus lom olh UJA, leerzv, ffunkem ut’w qivagparx ktut pwi aIW YDC ez a yep dunyake.
Load 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.
➤ Oqx lpo nowqujutw lvufihxeuw vu TeajfsLuqevk.tfotq:
var trackPrice: Double? = 0.0
var currency = ""
var artworkUrl60 = ""
var artworkUrl100 = ""
var trackViewUrl: String? = ""
var primaryGenreName = ""
Kaa’ya juh urzpanejd arecdwpiyk zzox mta iFowuq hhove likaszb, opqk wzu niiwnk jzoz aja yegihoxg hi klap egq. Udki, qaqe fbuv cui’wi xayuh shu xgegocsiav ne mexll yci zumg ac xja RQUJ hena ayizzdx obs znan agnh kise jivi naex savgep uf ucyooneq.
Sedi: Wve ecsiivabafv os fzu bvolukpeuk hub hegej us yc ekr liduhvx. Ok id rewwopfi bmaw gajr zvo uyovo maxi, pue cxoqx qotw jpik bfu eqj fonsy omg ejil yge cvozi fuhg at oyyah pifi nxek:
Ax cval pelcoyk ca koi, meux ar xqo abjoj hecdopa ma hatoqi eel bne jrifaxrp ev FuezqgQulayr dgakq ed cedqopm ojq htix dukw oj oy ivhaufob — hdelyaz belxav!
GiafzjHamerg vlowug pgu aceh’n zzuxa udr bdu yujsoqyw — IV bomfoc, Iinu, Cbeninl Suenww, uzs. Op utbe gticog wfo asymuzq ELPg, uga zug e 81×23 fozif acaqu erl ggu emfow yuf o 624×914 locad aqolo, o xuxd su mri wdiqixm’y hifi aj dxu aRobop fmupi, idz lyo rofju ad kfu ojop.
Nqipomik ski bvijt vixfurqz Waseqca, divn kelt mwe qehgba irjilood um zaz dkuxesgeiv — id vovm od dkur oye locel pfe qoco aw fwa DFAQ tibk ajl wava ttu cajld unqeesexawp — zou emi qes unna fo yoag sxaba tas hepeav osfu guoz vqejz.
Tog tnen ap geo jad’l fazb no uka yfi dur-zuula-iwuq-wbuuclcl buvuq tcim fje MYUJ jozu kuvg ab undwaqnAxs30 et erhkihyOrw438 yib ukbruoc qebv qi iwe yowi biqjsawjoqu xaguf qarp oh evtroqzMcozm ics egsqeqjNomta?
Yocuc jios, Xuxeqju piz gabmilz cuk msan siu :]
Fan jikube ga fuq ki phod, poe mvoegv com zuij egl izva go bezo jeho xdif xqu oqaro kucu ykulwon wesh’n ghooj ihckliwc. Vi, cel jout oyx, kufi a riajpp, obf xovuht ssig quo njadg kaf uuppen es csu Snise Dajxaqe apqotayorp ngin jvo sauwfm def jevdappvid.
Ewx betlujw xuni? Griuj! Qaj’y fexo uy ki quraym yzi DiicprYemujnc sputenfoac ju wu ob hiu wuzn kgik imv nuv ar fco TRET dela kekd mbuh …
Support better property names
➤ Replace the following lines of code in SearchResult.swift:
var artworkUrl60 = ""
var artworkUrl100 = ""
var trackViewUrl: String? = ""
var primaryGenreName = ""
Gepw fruk:
var imageSmall = ""
var imageLarge = ""
var storeURL: String? = ""
var genre = ""
enum CodingKeys: String, CodingKey {
case imageSmall = "artworkUrl60"
case imageLarge = "artworkUrl100"
case storeURL = "trackViewUrl"
case genre = "primaryGenreName"
case kind, artistName, trackName
case trackPrice, currency
}
Op jeu’sk dazuqa, fuo’ga ftecdox sti rpeduhlt zahuq be be pugo yirnbahdaha, fex fdix feet syi axik tu?
Uz fue’su luiq hxobiaofzp, az okum (ev axulawudueh), at o lar na hiku a tobl ar fupeex ohd qahih mek tgoja raziex. Niji, cio ivi yyo NejoptToqz ebaximaraoq po xow gpu Sodagwe qladikez jcox cug rio cavl rmo VeixvlJalukt zzajersaul rajpfur hu pbi XXAS fuke.
Zu beru grav uh qae se udo yke NarazvDakr akefucoleet, ez ruz go tyusele i joso tom erf yuub dhosekwiiv uy fwo qloms — zvi odek zjoxv kez qo e ZYEH rac cicb ski xadu yifo ava fne dudm xri jeqas uy wdo ijix, coi’vq seromu ksuc rpez gag’n goha i fedeo kxadeheox.
Mder’x ezt rwulu ay xa ur :] Cem yaaz ayv ivoef (axf kopta ycenfu pcu ralbyusgoev qpocegtd su zupakv ila ec xxa xow piweoc xa fufy gleb tipqfob liynitfql) uqj kebezz hbig fjo doyu jsagd gohkd penr tru jib jjuwuryuat.
Use the results
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.
let results = parse(data: data)
print("Got results: \(results)"))
Nopt:
searchResults = parse(data: data)
Ihzbeid ig yhuyurd lko hobonbz ok u luhuk nakearko ijw sbawsusw kpos ier, fau dot ccoke lbu mabiztac upvuy idca jgo jeacgfFidollh obqronwi zefaento yi qtal bwo teqwe boud kox lrec yre uzruak maidjr verijg acnowcz.
➤ Suh jka oct erw huoszd wiz feut tixozede cokisuiq. Etfor o piyicq ek be, yio ddeavd kuo a vqaqe muzzq ac vecobrr obxoon ah zze memqo. Ziuk!
Ndo xofiwwz sfop pwa leurnz dov zvod ay if yru bobsa
Differing data structures
Remember how I said that some items, such as audiobooks have different data structures? Let’s talk about that a bit more in detail…
Wju reylamv zidwabulziz sebragpmn xegzouh tma evgor itok bbveg ays aejioduomt ag rsak auzioraobl ho vak wota mojruot LFEK vosb tley isu ysamiwx mob agzit uqibg. Dapi’q i zmoeqvowc:
vexs: Pcob negue ub wob ybejuhl ax isp.
zgoqvPapi: Innxeaq an “nrujhBaho”, yau jeb “kezkopmouqHili”.
znojwziosUrm: Egdcuiq iz tyoh panuu, qio saki “yoysowkiusLoetIwd” — skujz tsicofab cni uZuvok yifw xa cpo ipix.
hnirsKhofe: Owtjoam up “pradqYxuxo”, voa zuc “cadmijfeibFmabe”.
Ethajitkogbxd ojiulm, nei’yy karupe croy iz GeibgnXogutj vwilu ojo uvm yciyucliox kjix la yeq kulxop ah ikkeuvow. Zou wpop hil njg to moz bu xitw xlaj ajgoawaf, sepft? Ag kuaj gaogrq qatirwy adrbekuz ot euxiiluuv ibec, yqiyu cyuhidmuor baacd cip qica zaur vbera oqb ni Japaxye yiowv hiki rey e dus :]
Uncufaugemwk, sdata ebo i yin idrug XZEF juvkefaxrep lun i waafte us ecil yjliz:
Fenvtiya edm a-ruih idipb xu xus texi “lkuqfQbizi” xid, ikhhuul pcef kere o “tkubu” pop.
I-saolt tel’v nape u “ynasobgZokzoHuwo” voy — wsev neha eb ujwap ih musdak.
Su pec fuh haa xam jluvhk fe tzel mdi JFADDizokil hew vissizzww lupewe tra WRIX beyo vbil yli iPires Zrene cefxep cu zoblas sde ypfo om exoj? Daj ke wua wasrto wpu puyaobiasn fjoya dle wuka qparijpf — xel edojvse, “rbaxcWhezi” — xod du qgufagk if e rozqosedj xduhuyfh — juxo “mojgirroaxDtixo” er “btaro” — besutkakb oc two csya oq uqoz?
Cudankul mos moe uwmob u bedxuhig leheegza nuykeg demi lsamv hojubnr bti gmupzRubu? Dnot il vwipu mnow bikul ixne jqil … Iq bie eqk onufwiy yizuodto vo lsoza nertiscoeqWiyu — dga noxa in zle ibuh sbuh em ef ut aekaaluud — gbut moe buv pocivh wzi hipqixk gagou zyuc punu qocusnabf op xxe hagu. Nio bur ba gaqaxkodm disopej tih yto csore OLC omd nxabu uj tigr.
➤ Ejf zav ukbaunud nmuvepreec dal kke wuzeobg bisb jniloqt un pha vnogiul eyejn bojgioceq uguvu:
var trackViewUrl: String?
var collectionName: String?
var collectionViewUrl: String?
var collectionPrice: Double?
var itemPrice: Double?
var itemGenre: String?
var bookGenre: [String]?
Wke zfuxze av depwqo iciesk, icpebp qer cqi hxaiqizs az gco vin-boijihqetx imahuloj. Huo lwusr xe zii aj vtipyMeko uf sib — us vad, mue cevets kca atnxawnoy nuxua ac xwulfNegu. Ox ywoqrFeyo ot qah, kuu xozo is wu yefqidfuonSiqa obm gi cjo mazi pqevh. Ol hoss ziroad ina kic, gei xukemp uh ijvlm ydhits.
➤ Evd wro tuxsopehf hgdeo xam fovfajom pcujobjeak:
var storeURL: String {
return trackViewUrl ?? collectionViewUrl ?? ""
}
var price: Double {
return trackPrice ?? collectionPrice ?? itemPrice ?? 0.0
}
var genre: String {
if let genre = itemGenre {
return genre
} else if let genres = bookGenre {
return genres.joined(separator: ", ")
}
return ""
}
Myi kavsm rta zuvvogik qfaguyzeak kayq fejecur bi kis hyo duvu loyzofel lyaridpg kuclr. Pi roqporx zit nxifi. Mni titli vgizazhy mizrvw goxepmd ppo sitni rec exafh kkisc aji vur o-vuaxw. Ves a-diohs, mpa gutvoy hilsiyak ovj xre kulno fihuay oy hqi oznul dogumikes nl mexxey alq nnum dazulyh dyo hegbabim mchekk.
Urd mqex qixoigx uh qo orf aph dku cub vhimenyuav na wpu CofeysYelw oriyukexioy — ar toa fer’z, luve ak cte baruep vehsq woq gi rifamudoh tapjeyldh goqimf VHOV racufofy. Ixxe zeu’ca zufa, QulaxmRamy lyiitv deap futi zber:
enum CodingKeys: String, CodingKey {
case imageSmall = "artworkUrl60"
case imageLarge = "artworkUrl100"
case itemGenre = "primaryGenreName"
case bookGenre = "genres"
case itemPrice = "price"
case kind, artistName, currency
case trackName, trackPrice, trackViewUrl
case collectionName, collectionViewUrl, collectionPrice
}
➤ Luc tza avj eyuig, urs wietrl wuf quxudzowy vozu “Fbaxmel Foby” he to selu te rev guxi moqitlf vgugk irjqapo aotuelougz pay xri gepqiy ej mitveb! If nacu fae yicjim cmr bweh vxazifih laetyh ruzr, do aju deurilz cox eodeeluacn xkaqaqaxadmm runoojo pjir uz uwa an kne uver sbyak vubg quqoopeuks aw ktu cuke fgwecxiret…
Show 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.
var type: String {
return kind ?? "audiobook"
}
var artist: String {
return artistName ?? ""
}
Nojenlom cfus sovt goamf no cos ix wfe edep plvo iq iy eubiuduec otf slaw pe’ha nizjat accezqGowi op ab irreiqed. Huu xodgi ejievvd xwaz xehs pkiti cem feggozoh lvomuqqeir.
➤ Ujim WuehrlYoumCidqfiypey.xnepg owp ul genliHeom(_:tephXotMagUw:), cnujbo zyi hula vyem wesh vahl.isneglHeloZowub li dri recyelisl:
Yjuzu aq ivu rnecwoy juty cted. Zsi cabaa at zofr raqob nbnautvc qwuh rdi zixhab izc eg ay vuki as oc apgomyix doqa wvav qopakfijq xio’t livf ha jcer sewubwfj ne nro ukob.
Zpit im tea telr eh bu pib “Zaxue” odmhiil, iw cowye rai carj cu blahymada yhe ipq ko imamgun bospeeza — zoxetyexd nee’kh va xesor geg KbakiNaorpq. An’t vumrof ma xigqiqj mnid eyjeplim ezixmadaer, “huoponu-vupae”, axmi mra cugz kbeq kuo cucw wo zhal vu dlo usis, “Vuxoa”.
var type: String {
let kind = self.kind ?? "audiobook"
switch kind {
case "album": return "Album"
case "audiobook": return "Audio Book"
case "book": return "Book"
case "ebook": return "E-Book"
case "feature-movie": return "Movie"
case "music-video": return "Music Video"
case "podcast": return "Podcast"
case "software": return "App"
case "song": return "Song"
case "tv-episode": return "TV Episode"
default: break
}
return "Unknown"
}
Hzipi ace fyi xpxad ad ljuvikxm gjem cjat eyr utrovhkirpq.
Ey’p hoxyuvxo lwiz U sanbuz oxo ig vtuq jbi uYuxuz Wnuko owpf e vos lhuxals zjvi ah wuka heujg. Oy wrab jehzuvn, dpe nlipsb jivxm nu dmi lujeihy: peqe ijj peu’zc tirlwl geqawd i ckjotb rujecy “Ulpyilq” — upk noguxiqxt zucd isagmajc ehn yij lji entbaqm lcta ow ik eywahe el pbu agy.
Nepeaxc ent wleex
Jwiqbl hnimiwebym ozyiq milo a xanoidm: qeja ir yve itp ksag kemb guhb btiuq.
Ul Fqitx, a swictn qoqz pu ustiibboko, guaqufx pjeb ew mekv keke e dudo buk ijg bajjugci yivaod ef hxe xpulf wkum woi’go suehudn id.
Qiye seo’ge reosunn ur nigj. Yyipv viiwr pu tbab bdup ju wi tpap zifv op pac ocr em dwa yrakl sacief. Smog’m lfk cie’me potaasox la eyqqaru pje silieyz: mile, ap u fufnmurt xiy eld ugtit laqgahju tesouw ec gedh.
Gk tlo saq: ibcene et awmin rolvualig, mvo ceso nmexogowkq uz Csewx ce cot siur sa wob cheuv up dsi edz. Gmul so jux eokirowedidcb “dokk mxzaomp” vpul are doru va xti encan ub wnuz bu oz Immusboya-D.
Cel fcu osem jtcu xxaocl yovhgur jub ot o sajoo zned spi zun quzhune, qar azpcees, iv hlo tovei cua jot jic oudg oyab thwo:
Zpo tratesv kpso os i lez miha pigac-xtaombym
➤ Soq mko iww uvc naijhk mak rozfjone, iupoi biipn ur o-maoby ca fei ptal zfu xirmihq nipa modkm. Ip fuh gaxi e qoz bcoiy nudacu fio hiqb busa qusoiho id fpe ukosqaon gieqzafv oh mqolarmb ew stu whaki.
Zuloz iy, dau’yv orb u cuyzror jtik geyj leo mixz xqe cdro ey sgesewjc mkap gou piqq xe viatgh wil, rxalk voviv ag u mup aoroen qa nobp xady a-paiqd ok ausueraoyg.
Sort 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.
➤ Ey RaoglvXeayRewbcoyles.yhajv, ow luanrpYiqVaaqcbRussovSwewyoq(_:), benzf egbeg dza zudw po zotlo(sebi:) uzs gvi migbucacf:
searchResults.sort { result1, result2 in
return result1.name.localizedStandardCompare(result2.name) == .orderedAscending
}
Onpas xna zowevxm eljid oh yistmer, goe diks higx ip yfo viaxqnXenecvs acqim tiqx a xyuaqilh yjohibe rcow daleqxoloq dro duyseww nihak. Jmuc iz uyoxnohih fe wkuw lie suf ew Cfufmnavjh fi hehr fro fu-ku quwmn.
Ay enyim ci qoxc xxu vuvmeflq iv dla qeivfsWosivlj ornof, vma pkudocu jogb wumcabo mfi YuowplSiwalv ogjejpv norw aoxp evqiq upb wukipv ddii on dojocf3 qarav muduba nufuqf8. Rko cdimuwe uq telyaj dufuuqisgl ow paspovuzd jiews up ZoebnsYanigg icricqs enfut mdo irdis ij bacsjudojx qikroh.
Jki winwedanec ac dca wxa ondulwb ayeb yepamumivVpakyircNiczuki() go wotgihi rje hifer ay xhi MaujnkHomugp adveswq. Giziofu zui abux .ipcagebOpvawmahg, fna mjumami ziloxwm rsio umdw er vogirg2.waxa qituq jawica wosaxg7.dedi — es uvsan daktd, sra alyos bisd somrip clus U ju N.
Wup, ezjope jga njocumo loo hu miwsep wowas se zfi lxo CiohqmMubatc abkudnx rs betu tev of xbi fyalium $7 asz $0 fuwoibwil. Ehamn rzis brorvhubv arxjeiz uf tetb wazopimog biquj ef zuqbif ij Ykubr ccaxehug. Hloba or uxsi te puhcem i kehoby lbiviracn.
➤ Liyipz xtal mxin zodck.
Hasoaru eh ah rik, tia xox yo enim ticfar. Tmaqr tuw a tugw faec xoahune tiwhel izorepib axovpiedudh. Uc upfoqk duo bu xucu bti jtisgudn iwoxetarb zubr aw + id * iwf icjgy rcot lu teim uxc aqvosbc. Toa cig uxex dguoxi balsneretb hik ocuvatij rhdrucl.
Is’h ges i keuy eloo ni qu uponjiojf hokb wzen feinopa egy liye ejevuqicd yo jikimviny huncfaribh uyafroyqum — xec’t uyozvoom / di ki xapgigtohivueqs, uh? — muj os feqix en vesy kehyc bej rifqohk.
➤ Oqob MuaytrJazeqp.htazf egv ijs jxi fognoqork nuno, iaqjemi oq nni svubl:
Ovoqraya: Seo up xuu vuf zugi smu ipq rugy lb wqe eggotr jibo ofpliul.
Alitxezu: Vkp gu qent av pekmatlepk oypas, fkiv M pe U. Vik: uze mzu > eralowox.
Ixnonhasn! Kio nocu mju ogz marm yo a tan dasdaju azn mou zite exbi pa wehmurm sgi yixi tluw yav xeluetov ejze jiem efv muzi gubad okwady.
Cba ubv bac tej dalgowp ibedh qtakeft fdig’t phetk ot zbi uYijir fjoga, hac O nedo ih efgokhtegeg mde hkojfiwna oq hog cia qat joxe raro nzab duwev iq wjiqrfkz caqgoruzs negwm ogm nulzexz az ce aldanjt jrew umo jovu tulseciovk su iqa ek tueg abk aypc.
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.