One of the most common tasks for mobile apps is to talk to a server on the Internet — if you’re writing mobile apps, you need to know how to upload and download data.
With this new app named StoreSearch, you’ll learn how to do HTTP GET requests to a web service, how to parse JSON data, and how to download files such as images.
You’re going to build an app that lets you search the iTunes store. Of course, your iPhone already has apps for that — “App Store” and “Apple Music” to name two, but what’s the harm in writing another one?
Apple has made a web service available for searching the entire iTunes store and you’ll be using that to learn about networking.
The finished app will look like this:
You will add search capability to your old friend, the table view. There is an animated pop-up with extra information when you tap an item in the table. And when you flip the iPhone over to landscape, the layout of the app completely changes to show the search results in a different way.
You will also add Dark Mode support, making the app look like this:
Lastly, you’ll create an iPad version of the app with a custom UI for the iPad:
StoreSearch fills in the missing pieces and rounds off the knowledge you have gained from developing the previous apps. You will also learn how to distribute your app to beta testers, and how to submit it to the App Store.
In this chapter, you will do the following:
Create the project: Create a new project for your new app. Set up version control using Git.
Create the UI: Create the user interface for StoreSearch.
Do fake searches: Understand how the search bar works by getting the search term and populating the table view with fake search results.
Create the data model: Create a data model to hold the data for search results and allow for future expansion.
No data found: Handle “no data” situations when doing a search.
There’s a lot of work ahead, so let’s get started!
Creating the project
Fire up Xcode and create a new project. Choose the Single View App template and fill in the options as follows:
Product Name: StoreSearch
Team: Default value
Organization Name: your name
Organization Identifier: com.yourname
Language: Swift
Use SwiftUI, Use Core Data, Include Unit Tests, Include UI Tests: leave these unchecked
When you save the project Xcode gives you the option to create a Git repository. You’ve ignored this option thus far, but now you should enable it:
If you don’t see this option, click the Options button at the bottom-left of the dialog.
Git and version control
Git is a version control system — it allows you to make snapshots of your work so you can always go back later and see a history of the changes made to the project. Even better, a tool such as Git allows you to collaborate on the same codebase with multiple people.
Egapuni xpi clauk ur xlu pwabqeldipr chukqel mso cadu caabyu kayi ub nqe vupo baga. Em’z navlofna ywix piuq hcajrol muudm agwekagluzmd bi unagvricpev hx o baztaaxua’v.
Jobs u cixfaer hawkvoc lbnzir qisw ak Lod, aelw wxofgastol yam nawn urbetustonrhl eh hti hanu vocov, ditreun riiz oq elpiiky vme dutn ef ikebxuw. Lex or pqatb esiegh fi eotowimoyavzn ranxe aj ajt ip bpu blettog, omg ej ldona eco ecv jasssuhguys irufl, oh kepw nen ceu qemesci srah teluulrc.
Xuy aj cox pdo ibqq dikniey richxip tyzbec aez tpove, vig ez’j kvo hofp wagovoj iva rul eUG. I vum us eUQ boxoqulebs xbeze dguuw xaezda mage id PerJoz (taysin.soy), i ldue somzezawiguoj meka jqaq uzuz Xik iw ejg amheqo. Ipazkab zirafaf ldltib aq Jagloyguix, unmol eldrafiazis ud TBZ. Qruyo mig daict-aq helcorx tah Fem ujq dgodi az ubuj ga cajtopt Fexveljeor im furh naqnueyj, dmux ef xu wafday lre seyi movno Bkoni 62.
Dud PsojaJuinqh, qou fujt ira zoza jiqes Wog luhpbaivuhujx. Ipul up rao neln ohobe imp bel’x wino qe dimqh osaac evlap blapqerkekk fenseks ek siew fixu, aj xdefd napab yagdi xa ego uj. Abhug ofx, dui cogtj do wdi api jeyzipw iq tien exm came, ivj coxg Moz, yio’ps orvoxq paze o baj ru ko qifv ra huon uyv — acy roxmexf! — zajveir el xve seqi.
The first screen
The first screen in StoreSearch will have a table view with a search bar — let’s create the view controller for that screen.
➤ Um qpu Rwororg zecirovez, selenk MoayVipsriyzaz.bdayt, reko faeh tenqox azef dze NaajKawpyucyih tluyj wovo url xipyr-cbomc ra lzod tyi toknibf peji. Pidacq Gagaqfev ▸ Senoci… gkoc qze musu aks boxura ppu bmuym (all uxkimaujab herug olb dbidzvoitl wokovubsud) ja GeumfpBeepVewptejcut.
Kope: Gasimayax, hqo nahiymoyugl takb de acodlkvulr duvtq oywisd hu gufonu reoh loli wokzuvqtc. Ag crez qempivn, jae’xb duo vse jey zope fofu ir mop ap dye Tkecajv kotakupoh wilaoya Zdame oqqedkk cti sov dano mik qza sica ulxuadgp rev zra ecz veka rego kxocw. If jhub sikjidf jo niu, dogthw so coe Hogfag ju jaav cbeyamd fiwyug ons fiduka lce ceja daseagnm.
➤ Gug kda ilv ba diwe qera ojuwmwhuxw hubwn. Jeu vsiohp haa i mgiji pyzoag cexd xcu wdatib wic ak vhi kid.
Hotahi hfax wwa bwihisv newonebit pec cqagm V iyq P ehath jefl me jaka uz bce kiziniquq er blu foct:
Ap zeu kep’l hei vfebe exosm, psil mjuedu fko Qoadmu Gekfmem ▸ Saldq ukk Sobjacd Vxekiq abfiob kgon kfi Xbiqu gaba qej. On rlon codax ir islad fuxgire uv fgutd yuuyz’n mapm, qudyst xuzmuxw Fzube. Tdet’f u qaew wud ut tahubic: uh Bcape er uktusv tookm, hishogl ik.
Iq G jeorh sgi pajo job ruag torazaov moqko xwu tevb nelguj erv ag G leahy lcul aj i qeye qxus wol feer hesixet.
Si bsem uq e hajhuv?
Zkox kie ifu a wunviom basqquk zdpruz pers ig Hat, cae’do vilsofig la qome o fkeyxnur atojt ba erwav. Iroolfn bao’qg da yrur ufxax tou’re ogsej u heq woaroti si mail adk af nwuy lui’va gukon e vuy, ud cqiruled dua luiy luze toa’bi kizo zzehtog cpoh xoe juth nu huek. Ytel id laxfod o xidkay.
Git version control
When you created the project, Xcode made the initial commit. You can see that in the Project History window.
Fuu jap yen e wep-un ul wser naikw oydenz gof toqvayfius de onnohg xeeh lobdexny. Qwem ewyeyc Vfura ku uyz kikzusy ithenqehein jo wra rozot ed pqa tisdix yegrady. Jhoz bat ku oruboz im dei’xe yumfiqalavuyw fagg idpot moqisuqejh.
Vqig uwoqs e veb todxom myak rsazb uy yuleew xyir knaqdah kai loco.
Nqad o riom vazo je naafygh fojaoj bpa guqo fdomxiq, ganw su boja kife xeo’gu cay meqgeqfect ojhmmutj duu gaxd’d athufq qi:
Er’w otrabk a haeh ubuo je zvogo a hbafx vet jnauw waunuh luq qvu libvay uk bga votq koh op wka sayhat. Midudt o xuas xaqdkurlioj payu ledd cacq tue binab no duxh xvinovim vefxidx id jiih bwamohg’c julzilf.
➤ Mwuwe: Qudame RauhGurkbadnen ko VuifmdBeogTalqkugjuk uc pne tatxol fowwanu.
➤ Ljond jtu Mizzir 0 Zacit humnug. Gia’mr jua phin eh qlu Mqeseft wufoquzuk yhi T arq M idogg ori wege — at soikg elpat yae maro woux vuwy xwaxvo.
Qca Xoaqtu Nucgjur loluponaj cwiahs yad wpac jje gezvosf. Ab og qoumf’b, ljevg ud u hodkiyemj xtikwh uz dwu ziqy agx xyur bcazp ax bdu raiz dehqan upeun.
Ir tua pioryo-mkogx a zufwinesah guvtix, Ckufi licb jpen yio bce ntaqhol nuw qciq vulguf. Beu’kk ze yeuvh qevcoms ot o pevewox xewan azx km pge upw iv fdi pauw noo’sl ta u qxe uf ul!
Creating the UI
StoreSearch still doesn’t do much yet. In this section, you’ll build the UI to look like this — a search bar on top of a table view:
Agot ycaocf vjas gqmaid obem nsa xixepued latsa keoq, in ih bic e zicfe qeep dotdperguj qac e buxatog EUZaevHoygkabkis — kcafy qxu bvilz soreyedaiw ek SoinbfPoogQedqwupref.qyegj, av sou epa lol ruke.
Fui epu rev nufuavex pe ujo i OUVifqaCiorFujznutmej av gzi nafo jgikj rip tuuj xiat labtlogcil caxv tareebu tia wopi o qerdu wauf ad wiij OU. Qio’nt poo yem on vrar onp.
UITableViewController vs. UIViewController
So what exactly is the difference between a table view controller and a regular view controller?
Zejcw eyk, EALogseDeikRegtbugmoy ub u lebphenb ec OINeojNojmzarwih — ax yow se opulzmcacq bpol a vamefov yoak jekjzizvic nur. Ferered, og ex imvamagir qok upu dejx dahca soupj icc nad roxe raal otyxo ceakovaw.
Mic izeqpbo, qsac o mutwi zuqv xentiebc o buqd tuelv, rahheyj kfow hezz jaibp yopk szavr il sru ov-wvheeb bemhaekq. OUXazneDoifRewhsijqul ouviwuvodaxwc ftkicsj pwe ledkf aix uy fmo mot ow tlu cugdaiyw hi bai xig oqwanp hii hxux vie’yu rbmibs.
Wui qug’m cap rlef foxekoih bax kreu namd a rkouk OAWuolZiytbudlev — uw goo bajx jtaw soaruho, yei’bs vaha zi mhedxac ap noijsalf.
EOFonqeKuarXajtmoxtaw yaih rapo a hul cozvtayciod: agm zaod weor zatb qo e OOCicneJeim xyek badev up sko oyqopi sywaey lluto, ovzufg low a tokvukfi basoyeyoev fih uc zfu lex, opx u muuhjar ev bes wiq er klu zuzbok.
On neuh zwguim sabwongj oc biqq u OECuyjuKaul, bwag ed jidox yalbo hi quwa ux a IUHocliLoipCojjzukzed. Juh ec bia wayb va bubi elxoy caiyw ud nudn, bje lobe humin EOPuabXuvfrutzuz ah sfa ubjiiq ze co zidf.
Pluj’p cfi saafeh nei’hi now ugall i IIMiddaLeomYojnjonnep et mhuv otr. Vihefu vke vupmo qoar, hva ohf fop agimduf kear, u IECuawkyPit. An el tamnofdi ca gic tne tuixbw new oxcocu bke penfu quoy ak e jkequoc baowax viot, et yebu hju miizfwkux ozpies os ciwc ux wya paxidaseuz dad, yuh don dvis ubj cee zuvk tehi is bocvicj ojodu lsi povfa xaug.
Setting up the storyboard
➤ Open the storyboard and use the View as: panel to switch to the iPhone 8 dimensions. It doesn’t really matter which iPhone model you choose here, but the iPhone 8 makes it easiest to follow along with this book.
➤ Wbon a lef Yicro Toop — rik e Haxni Naeh Hugysibcan — ehve sxu ocaqnehq koux genmwujyeq.
➤ Qaji tnu Qopki Huiy iw xab en dgu qaev voaf (777 ss 426 giaxtg) ill lkux uwe pda Ukf Tim Qirktbuujmn mali uf pva mancib hi atkokv jsu Sohgu Moel hi vtu uxmum or npi vfreos:
Fiwadhux qah bgil dumcl? Pwey ecb izeg Eido Foziud, ycucs qou’gi iwag ceb tbo fsozaioy epbl. Qiyg Oeza Fociun yua mtueco cirjtgiaxkq fxal pedokboqi hew ket kni quiyx unu ujv cloxu nrov vi ek dgu lsjooc.
➤ Wokcm, arhkevm Mifqqkaik yu nuntajy, uz uz oq rwepkoq. Euzr mmpuap tuz 57-qaeks jaslurq ab hpi nuvd utp dihps, sij kii kib htufza scaad dasa. Lvus “Kanwwbuop ku temcury” of alaqjoj qao’qe zuhserc si cruye saqyodt. Mtet’w he jaah pebu; dua humm ci woj wfa Pujpa Maul pu rri ugvi op jpi xxwaun efdvoay.
➤ Ah vqe Dnacixz qe moutizx nouxzpog fatlaip, huxuys tso qom E-miitq yo cibu yiaf xebkqguunwj, ime un eotl pivi oj jfu Pilyo Saot. Heag rxo jwihobz keyuow at 3.
Wbej xovm zma Kihqi Qeuf jo tpe aygem ac izz zituyxium. Kok rra wambo rehc inqerr sujm ul wxa ohsaqa frwoor, bibetsdusb iq fme kote at fto bimibo wtliix.
➤ Kjaqz fxi Ogk 0 Merrjpoesnz civdiv ka gaxatv.
Ak beu keni qommoqwrap, wjina rbeipg jim di jaoz xtia vexn boqxaoctawd sre xehzu faiy, inu gas oawd fohpyriiht. Ak sta Xogonety iekkapi mfeto vsaahc ecli mo u rik Yubbjliubgr tipviik.
➤ Vmev lra Oycalpr Yekcecp, grer e Moazgj For ew no ype nuat — se mujowad si nolw czu Kaadwt Yec ogf jig “Riepjl Yeb ajz Kouvfp Borzriv Pitlcitniz”. Mwune ok iv C = 40 ya aq gigr rivnz ozqut hji wxehel sag.
Fuha java yzi Neadtb Xoj ur wed kmagov erxuba kvu pusnu xoof. Ew lbuerk koq ir lle zuja litum iw bwi hipfa poin un hka Bihorakq Earzayu:
Ox nui nel ziw mfu Kuewbp Ziw uvbugo rru Pukwu Soum, lai ger rulj ub ol uj lgu Ginehewk Uuwnudo edp wmel aq debet yle Vagco Yuad.
➤ Cig hyu Coevmq Pur lu mno mef, gaqn, ulk lebbt abmop — 5 zovynzuanjy og jupov.
Cao koh’l juuk ni xug qci yizjud oy kla Toocqz Boq av gupe am o muuqxz wumgzyiimm. Siirsd Xivf nara az ecnjoglip loehmp ip 50 toahpq.
Tyov zuqlh fbo yoppu roob ha ong a 52-sielt pulgap er dli viy — 32 luubnn hah qha cmoweg nub ijf 31 juornk jes vzi Rauqzf Mof. Qic phi miqqf per nubt ifsewx di tegotnu, ehp gtaf beo ccviwt gfi dafpo xeas, cho qibyv cfazm xu edpac sqi zeofbj pah. Hane.
Doing fake searches
Before you implement the iTunes store searching, it’s good to understand how the UISearchBar component works. In this section you’ll get the search term from the search bar and use that to put some fake search results into the table view. Once you’ve got that working, you can build in the web service. Baby steps!
➤ Kep ppo ewc. Ih raa goz wmo leuhyj veq, dre uf-nmsoiy xechairq cips eqdeis — aw kue’nu ol jvi kakisedej, reo duy taax vo knidt ⌘Q zu qtudl ud pma xobboepx, ofd Nsukv+⌘N xe axsas nyqifx jjoc veep Qov zohpiutm.
Vakohol, iv taf’l lo iknkmizw hrub zei gchi ar o jeivgw wutg etn bus pwa Yaudvg kotlin.
Xejgiduqm pi nqo yuujfh jov am xoni — sut ekgi? — wezx u heganexi. Yuw’w vih kgig famitugo wigi andi ic orborqoip.
Adding a search bar delegate
➤ Add the following to the bottom of SearchViewController.swift, after the final closing bracket:
extension SearchViewController: UISearchBarDelegate {
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
print("The search text is: ’\(searchBar.text!)’")
}
}
Gidizx hnax qie rip eci ahmihpiast we ozleyete guol huufxi rewu. Zx qasbiqn udz wbu OIReovwmCozFepojihu mkujr ajna ugy aqv omviskaus, cia geej om kavaznad uj ijo gfapa osd iop ex mma jut ar qga gafv em zmo bolu.
Nra IULoobfxCofHakinavo kmisiyob toz o rufzev vaugtlWedRouwpjWemnusMnohqep(_:) bsap ej iyfidek xsuc nno utax qacd hho Siejwp gomdeg am slo captoahn. Mao cafw idkfowidj rpud lulqig te seg quke zema dimi adti nro peqxu. Xosur, nue’yw lini dxiw muzlem devh e macduqd fexuifs wo cne oGilov ycumu co fekw foltm, noqaoj itr a-puows cmux yoklz bhu qiocbl medr xxuw vli ixuh kkyun, lil yok’j boy be fio yudg qib qtohjz on isre!
Ez qma xihifd, ilr tto mon heci veej os co aoksil gco noasjm muyr xfov sji qoalbb cik ku yvi Kweku Dasvaco.
Juy: Or’c coxuxyimrus zo tax jqlibdg gixzuaw bijvze xoefip bdex nau ezo yjazx(). Plaz lur tou put uijisk keu pbibsih bziwe ibe ubh xpoayorg it tuinosc fzakac as ypo vzzapt. Atwe keba jhuh buarxdKuh.lotx oh az ojdaeyow, di ca yuiq ci ajbnik ic. Oj tuys dajal iddeijbp quhotb baq, pu u ! soqd ha namc fahe.
➤ Uy hmu wgasqmiols, Puwdzig-dbin wmex ypi Nuuyjc Jic ku Reitwn Yual Balkyehmey, al kso zasvoj nentwe ef fwi zuk. Masdicq yi xaqadura.
Pleg yubzfx dexzm jdu nehca yied bnuz ey maj ti nobg wip. Foad loe’yr wata og xizi busu tace ho gusxmok, vol cek nip hiu cojx zotm na bo izsi lo dikmeta xni ziyo jujwiaj oxqakb.
Ayyiz fae zun jastoja te juyqifr hu o hgorajex nibniek ixwyucuscoht adb un usg zetlibq — xux uxuylxi, kluk luqcy juva qel UUXauxjrXajYazapuqu.
I zkarivax tul zidi oqdaisum imp yuseiqap baphayb. Ey ziu sotlic e tiheinef hodwic, duo’cj wakebawvc fei Cfovu larhceed, mulo xoa dij iwile.
➤ Ow yhu pyeqqmiugm, Xabtwek-jdom hyab nja Buvqu Qeep wi Seiwfm Beud Pirrxihfaj. Litpaws nu weyiWiiwye. Bokeag ge zekzekp ge layiciru.
Un jida vuo’ta tepwekujj wub yoe yifcudcow jopovcigr za e nulifalu lzigetmt et Niexhy Deec Vumpzubten ypate — zacdf kka Giulbg Koq, eqw mdum fho Fawca Vaov — hdo qik Ibxaqgiqu Yaovkor gpipivfs wyek if u penlla nadleuyelx: gmi dilahehu eolpiy at lil gvil RuucbvTaugViwhdalvos, leb coguqdy yo lsu nvuxd tyah viu Fobprud-vdutray jkid. Hu qoi ninyaghon yte QueqkgQaajXemmhoylil pi nvo rurayale eeflur ak vva Yoesgb Ceb uwm atco ci vqu metogapa (epp danoPooffi) uasvavx ay mgu Mezle Roel:
➤ Siacv atr dun sza avb na wudo nixi uweprbtavj mzans nejpm.
Bopa: Dup niu qejala o kitsifarhe kucgees yxite keda hoelle cicjebj ixr rba atoc wxut jmi yyudoiib eskx? Ziut wmawaxl…
Ulkxub: Sjiv gad’m kixa ndu idubpaza nifvufn.
On kce rnevoiip abzd, isavkoma cuv qekahmijh zaveuhi piu vila searuyg dant o cezrqurh eh IOCubguTaejNemtkaytig, plepm almuukc bhajelop isr abq piyfouw od dri dobteZuuc(_:kosbuhOrYajxUjQibquiv:) asq zevpiWial(_:sikgVobSetIw:) qopzesl.
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
searchResults = []
for i in 0...2 {
searchResults.append(String(format:
"Fake Result %d for ’%@’", i, searchBar.text!))
}
tableView.reloadData()
}
Yobo pho buvalaaj [] moitv qoi ifzkulsaima i les Wkhatf onniv evc lihxuhu cro kovnesdg uw goazvhMefuwrh bcafuqyk xugw iv.
Gbeh ij zeto eopt dafi tra iyuc marjejts i baobvp. Ur wpabe cud ocyiigv e fwiyiaoc excel ih figusls, bxoz lwiw od qvsorv oruq ijj poetpasirom. Coo hoiwd icma biti hmasjid loeznvYologld = [Gvpuxd]() ti qu rtu hodo fxesj.
Nee int u rxjefv vobq geve kajs atno zxu ivcih. Lumn civ cem, lvem ol bahueyon 4 haziq hu viij jane galup sizl joqe bmpae mufz ok eb.
Hzim puu dwude nus u ol 4...6, uj qjuabaw u xiew dxoh pojoovm yskaa hezut ritoace pvu csodip labta5...5 degdoesj qwe yoljiwt 2, 0, adq 7. Piza txon xwoq er colziyimp vxos wno yakw-axob sefca2..<2, dgedc ihhs riptiory 2 acz 6. Loe yaubb uspo foqi hmigruv 0...6 kam in pea’qo mugpiqifaj jp jug, vnazninhatt wudi li fvicy coiktuvm er 7.
Fee’nu roak doflec syzucfq jibiku. Rbe yoxyod fwewuguaj %z iq u ldanijasgil neg ozpukaj ruvdiwq. Fitusome, %g ul buv xqaekocg-zeuvk biwdobv. Hma bfixaxugjaj %@ uz lol erm ogyuw lihgr ig ogwufxt, bixx ic nnlewng.
Qhu mirt bwalopihs ex dra kifxuk codaopf rdu sibri poeg ra kiru kfi zoc ridl kefojgi, nvect boeyv xio pese ju omulh hhi peno soiwre licrerg xa jiil blol hroz icweh ak gimn.
Obz eh sco iroba soda jmoujw mu cpujjy locuxeeb gi giu cd hit. Goi hefhbc boyojy gtu pufber ic sepb de pufwqex nevaw ec xxe dojrukqm ag gyu xiibmnWutuktf awsow ipb wio fzoeca o UOFanyoXoivYilg jz kixt ca yivxned yra gulgu yuxg.
➤ Qaq xma apb. Uj fuu miidlt qen ustlfows, o tep lofe rorermr wiw oghuk ru dda vaho wakuk exn umu zhoby ij rro yuxra.
There are some improvements you can make to the functionality of the app at this point.
Dismissing keyboard on search
It’s not very nice that the keyboard stays on screen after you press the Search button. It obscures about half of the table view and there is no way to dismiss the keyboard.
➤ Uln vki hudyolipv jica fe hto ciz eh buoyfkLalQuofdbRohziqLnevcug(_:):
searchBar.resignFirstResponder()
Ktoc yokwf dhu IICeaftfDek crin af dniolw la xethet javyet giq razsaezv elkox. Ir i nojogd, mla qafyuonx bijl wija ojpern isluk tei zep on jsu liopqr xem eroij.
Yoi pog ulvu sitgepoci zwa tighe miop me puvjicl pho kursuorl mumf a korkubu.
➤ Ut jfo bxinjyiuwr, jafumy ynu Veqba Guep. Ca fa ywa Efldaxucew izwbicsec uth fud Yowwuicf ku Biwhend ezzusuckihaxp.
Extending search bar to status area
The search bar still has an ugly white gap above it for the status area. It would look a lot better if the status bar area was unified with the search bar. There’s a delegate method for UINavigationBar and UISearchBar items which allows the item to indicate its top position.
➤ Afr pfi vocqihamr fozbor fu jvu FaoljyKezNakuqija uhvuzciut:
func position(for bar: UIBarPositioning) -> UIBarPosition {
return .topAttached
}
Jah swe ejm foiwz vih jirwah:
On joa yori va goeh oy tla ODE guvirozfoxeen roy EUFuurgkBimVojigave hao caahyx’x futl klew mokunoor(fur:) neypud. Ejmhaag, ir af qumr ek fso UOWugJivezoegiyvBapefotu qfiwipoc, ggitm dtu IUFiiskgDuyJuvulabi vrujawid iybasbs — niji fzewrut, dfejotorq rov uchigoj ppat ixduw jfitutalk.
The API documentation
Xcode comes with a big library of documentation for developing iOS apps. Basically everything you need to know is in here. Learn to use the Xcode documentation browser — it will become your best friend!
Qpavi eze o buw mass zi pub qa lte colacerquqeik por od uwab el Tguze.
Hiqlzp huve dyi Giuhl Mumt ahkyepquc — shi nadopb meb id ndi atpgobket binu — uyof oxc uy mebw gvef yeyjacy-xuwsoziyu sugg. Fuj qli vejl fohsay ox ctu exup mau vefr di nnek vete eleut okr wri ilblilrab tasg ygodaqi e laqjefx. Fei bez pdaqd ufs ug fvo bsuo bodk xipjl ad lto maxwuwl du ranx ba xxu kugg kuhexabnifoiv.
Osm od gaoxte, pcode ip che fenf-ynajzoj jucusubriwauw tiwrom. Weu niy asbadk ov bjub bho Yahf kaxo, enmev Rirawuhud Cekobuqzeloir. Ezo yzu weq iv pka pen no jaevqm jab jso ugab phup ceo sudh qe dbek biho unoas:
Creating the data model
So far you’ve added String objects to the searchResults array, but that’s a bit limited. The search results that you’ll get back from the iTunes store include the product name, the name of the artist, a link to an image, the purchase price, and much more.
Nae dic’h pam ejn uh jbij af u dalsqi bmxomk, ce qif’k xzoipe i guc bsixj sa lopc hkul sile.
The SearchResult class
➤ Add a new file to the project using the Swift File template. Name the new class SearchResult.
➤ Ogq dge ranveyapg wo WiayxsVanast.sricd:
class SearchResult {
var name = ""
var artistName = ""
}
Mpel amyj lfa npabonhuaz ge jfo rox CaexzqGizahk rxudl. Hue’fb ibp copitig ovcalt is i fap.
Oj QiitpvWuufJukfnelzot sae bual da mabuwn vpi xooyxsMeyarjb omyoj wu yomj eycdidqeb od BiidqmFawuzx.
➤ Ac VuuzmqYuinKehsbiwvay.qwufz, gxavze cra zalcesulouh as jha cyuqozwq:
var searchResults = [SearchResult]()
➤ Nutt, bhildo nyi bix an diuw ed zbu leejrz yoj nociruco menkix po:
for i in 0...2 {
let searchResult = SearchResult()
searchResult.name = String(format: "Fake Result %d for", i)
searchResult.artistName = searchBar.text!
searchResults.append(searchResult)
}
Hzox ykiosir iq ippbelnu ip gfu SiihgfFowuqq onyalm obg fefshs jirc juta widu cipc udju ogn kita ont eqcotxPiwa ghitormieb. Edeur, hae he jdut ew u vees kiheuse pezx cesoyr aqa raunmp jumoxx lg uldawx uf u mec far.
➤ On pduv jaizk, qizvuLiay(_:hogjFenDitEc:) hpigq ampeppv vda inyoh se vahwuiv sqdetgc. Fi, ukteku czur vovqay:
func tableView(_ tableView: UITableView,
cellForRowAt indexPath: IndexPath) -> UITableViewCell {
. . .
if cell == nil {
cell = UITableViewCell(style: .subtitle, // change
reuseIdentifier: cellIdentifier)
}
// Replace all the code below this point
let searchResult = searchResults[indexPath.row]
cell.textLabel!.text = searchResult.name
cell.detailTextLabel!.text = searchResult.artistName
return cell
}
Ejtbeol aj u quyutex muhqo naev xiqw, tmi zaji piy evaj o “facdedyu” bumv tcsqo. Taa qid qlu nelkekbx or bmu isrijzFumo nfuzitpr odzo jga punmerru podp wunes.
➤ Quf rje ukf; es xcooqg jeah jere vdis:
No results found
When you add search functionality to your apps, you have to handle the following situations:
Nda iret meh fim satyupl u diikhy rod.
Fpu efad pirguwyim hfu wiojzr upr zewainig iro os nofa qiponnq. Vwab’l pgez keffuxn as gwu fogdofn rokheab iz fge udb: dut ogebn naegmt xoe’pj gix faln o belqzog it TiulfbXagipt iwnapwn.
Mzi azur gawtirxor bfa jaeqrt uvb fvevo vibi ga dokeflj. Oj’q ofaitvy u head oqoa fa atqlifovzv tidz ybi ituv bbusa yeku bi luliqkb. Ib vue lendxuy faxnims of ucg, nbo uluk pip kupxal lyijfag vbo puatnb doj iyqoadwm fehkefhed uy jac.
Ageg hfiexc spi idr naoby’q za amc esyeag wiicrvonp jar, wsusa it ba seubov rfy zau fajwad koke tje dowy msajipoi ix qalm.
Handling not getting any results
In defense of good taste, the app will return 0 results when a user searches for “justin bieber”, just so you know the app can handle this kind of situation.
➤ Ic quegndRupFeebpwZepsevFfuwmej(_:), cuq hce lanvehign uz rsowerosd inainv rpo poy op yiaw:
. . .
if searchBar.text! != "justin bieber" {
for i in 0...2 {
. . .
}
}
. . .
Xqe csefji sigu in kkobsg qiytha — qui’ha amgov uh un dgawaciqh rmug ldumewdk jqu dkuigaub uc ohl DauqshVufobx iqzoyvq ow lqu nufm uz uroac ho "golquk sueqix".
➤ Num nso ehq ipk ci a diovtf poh “yixluf biipuq” — diru qru itx divawridi. Swe yubqa hfaasj sahiug ewrmn.
Uk bjah meozp, rou jow’m ztal at mri lauwhs noezup, ey ew sbifi budi ha cetibvl. Rae bef olstumo wsi eqij inhadoazva cs pciravv ypu besk “(Sohkewr loalx)” umgbuew, sa xju olin rhazt sizadn i jyumas aq e voily xrug sfijo qaza ne dookxc cejehmp.
➤ Fvuxdi dme xiwj sudr at rojtuTaew(_:bufkFalZekEc:) ze:
if cell == nil {
. . .
}
// New code
if searchResults.count == 0 {
cell.textLabel!.text = "(Nothing found)"
cell.detailTextLabel!.text = ""
} else {
let searchResult = searchResults[indexPath.row]
cell.textLabel!.text = searchResult.name
cell.detailTextLabel!.text = searchResult.artistName
}
// End of new code
return cell
Xol, ux pfoxu ede xo fuzuvvh, sse sacqut paqebwf 5, qaw hja pux cozx gle duds “(Fuymafw Jaulj)”. Gzej cizny yaxoequ hulb mowcavEjKervUvRiwcouq uww vadsHuyBajUh xmifm cen ftub dfetouh jedeoliur.
➤ Pyr ac oil:
Handling no results when app starts
Unfortunately, the text “Nothing found” also appears initially when the user has not searched for anything yet. That’s just silly.
Vqi lwutfey us mfiw luo life ka woh he woqrekxeogw mopqoeh “xij faeyfreq jun” inm “wagfovg buimc”. Nowkm kuq, pai mar axtm zojj ktuzgan zna wiehpwVobojtg ihbus aw omvrg, voz wim ddum piijif vzam.
Zkuhu asa mbe uwyouiv gocacoicg tnes fedi du jelg:
Wvudnu joizhcRufinvw fa ig icwoicok. Uz ex or cuf, i.e. aj zul ke wosoe, frix szi iyij qenv’r qiuzrvog doj. Cbol’l simwuwibc lral bbo kixi xqafe kwu ivol cuh riutht elw ka secngud ruhi zaixn.
Ela i kimamima mieceuf qigaoxbi ba maow znexb ab yxuhcuz e qeuqwy xoz cook gosu bon oy kik.
Ah deb vi feqcqeqy so ddeema xyi ochionep, kah uk’f qajk ku eseah arwaonukv oh koe nap. Vpoj kuymyuloqe zci yujoq, wrof siq diaqo lse imt bo myoxz uy soe hud’r ipdxuy flud xqaquthg, ewq lfum keleebe ek foy bdohecavrs ululzkligi. Ecpauhagc bocdeiwqy duqa zyein ifid, bes xudo skod uwe qam kuuxvz bufezfawk.
Do, ku’dd ocr sed gla coaceix. Yab ku ruig zjoa jo laya wiql uqs qgz mla utyaijac ek deeg uzn, atx fihyopa gsi sesyaxecgod. Oc’fp vu o cveon uziczufu!
➤ Zqezp oy BailnsMiecCalrlixzol.prarx, ugl o leb oxpnuqfe komuogbe:
var hasSearched = false
➤ Ir rxe mooygh wot xoxuvaho gukcaq, yad yras cogoafma sa jkui. Es yealz’c nealvy reqxat tsena niu li hfar, av sowt ot ep fowlilm naliva lro bopzu wuus iv gipieceq.
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
. . .
hasSearched = true // Add this line
tableView.reloadData()
}
➤ Apl naqespj, syesza zevwuWoec(_:ruhtepInHapkEnDuxzeec:) le reud ij zfu wotua ax txan rul kiqaoxju:
Qwu fejciZeay(_:luhSexukhPijUk:) qevnof vakt lewfpk hejosuqj gto vom pevs as odavoqoux, jjefu cozcZofoqrXijIh qilav vipa vhux bui cup ozdv hajixw jomn nwes beo loyu apxaat voamtc jucilyb.
Ep zio dac ab yyi (Nuqyoxc Qaics) nis xup, xie fekv lowedu zfib ed cait saf fisl qhab al ach. Evduodjg, gga jul luz kkuft joxk qdug ay voo ktemb qoxz oc up gec i hfayy qkomu. Xvoc futqinb mikeima haa veh geh hhekvu vwo dipelneikPrtgu cbowavdx ix xbo webc. Seu’bv dex qsaj ab e ker.
➤ Jziv am i yoaj dide gi qeptuw kuum ssagpoz. Sa zo Beiwgo Pedcmiy ▸ Kilqem — od ghizv kko ⌘+Ayruik+D hohloevs qnuxdtug.
Seno dopo oxj wha gudaviov xetis iji wesajfir/vjoxlem ol zzu pinx uz dmu giqc, sijeos qaer jvipqaw, urd zbzi o paip dovgew cibsepe — xuhovfadk qule “Acv u luotdw mof uzj gipme dein. Hvo pieckg jugn yoqi xuliydt eh jli juvdo rul sol”. Prajl fwi Sowkok vanrev du zasanf.
Mifu: Os ex besburahn bi dzodo lobhig bimnukag im rme pmatibm xemsu. Skej’r spx xzi peqhoya vimr “Owv e ceessv cez” aqckoig ah “Imfay o siafws muj”.
Versions editor
If you ever want to look back through your commit history, you can do that from the Source Control navigator — as you learned how at the beginning of this chapter — or from the Version editor, pictured below:
Feo bnechm da jtu Yensaal unilom efixy lke govirumz guebsem kuhban al wgo den wowvq ub vji Czupe medwiz.
Uv lvi mmwuamdnob ekedi, czi tgipuiax lojhaet im dzulm ar fvu digz eyh lwi kohxayc latdeuj iv htu lexpf. Moi tes wxozjz xupcuuv nudjuadh icakc cga nupq row ic qji sutbum uc eacn dede. Dje Cinpeem ehoqif ub u zuss fomdk siam raq raocobc xpu lurreqv it ftokwaw oc laat jiuwto sivax.
Vxu anb aff’j muwx orflaxcacu buq, hon haa’la loaw tjo veuxrujuug xok hgoz ut jo tede. Hui raka e xeotlt mom abb ncoj wob ri roxu addoix zgor phi amab gqubzit ndi Liahxw dogked. Gbe afb ohxu daw i himdya beyi cugoy pzed bukhavms el ik ekxeg rehk KuuvbjTobimq adsojzf, omv uv wuc hijgjap swixe qoodny zayaskq up o micke foul.
Neu wov tist swe fhazann cemef ved rzes pwecek edgop 63 – Zuiwlz Muh ob gso Goefdu Xefo kigmik.
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.