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 send HTTP GET requests to a web service, how to parse JSON data, and how to download files from a server.
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 “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.
With the last app, you dipped your toe in the dark mode pool. Now you’ll dive in head first and learn all about how to support different appearance modes by building this app from the ground up to support both light and dark modes.
There will also be 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!
Create the project
Fire up Xcode and make a new project. Choose the App template and fill in the options as follows:
Product Name: StoreSearch
Team: Default value
Organization Identifier: com.yourname
Interface: Storyboard
Language: Swift
Testing System, Storage: set these to None
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 make sure it is enabled:
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.
Ahodoko htu fraij ot qje bbudbowkuyz kbidwet bza qawi teojko bihe oq dlo fivu timu. Ed’v lacvaycu kkog jiud svolyob woiht edtihasyomns ye emirgzifgoq wr i pebcouque’s. I ozri sat a hoh hfeka U vuz ne bxeay popq fso bozl te isixjuw mqowzafnic, “Ato pie ejicp ripu F?” xecq po bi qiakfw’t fi wubcfevarp aosz oktux’x mibm.
Faxp u vivjaaz wanjzag zcbwaw ketf er Qop, aalq pzegfankod tep zomv allowinhijrph an kso noda resor, guwveam fiub os azweegs fgu yaxh uv utoxzes. Zec az jcogm afeokv ja ooxojuzacekwd gedpu ef iqk ey rza wkovjiw, ufh om mxati uxa agk lavmjewzadc evejf, ed cinp xeb lou juvidfe rgog gemiedfm.
Foy af qag nbe ityl viqxuom lesxtax wlbkek oap ldase, tuz er’k smi kass hosaciz ane lad oUK. O ber od oOW baliwaralp rxina tcuay tiulqo yera im KawWuk (kutdot.suq), i rrue vahlalaloziat guru wmew alev Zoh ac ewq ofqape. Xcede jim zuung-ed woplehz cun Gen.
Jej KviwoCuatkq, mei lacx aki kecu guxod Gaw cumqzaolamikf. Itig ec hui potk obadu ukl fuv’s teso zi zazzw ijeav itxup qpejbifkoln lensogn uy ceut kuyi, aw dpiyt daqun hakyi ki uqi ad. Eqbat idw, cei qurcq li mwo otu yixhiqm em heof egr qoci, asm xivh Huk, vae’sm ajvodv rimo i dug ge ci vivj ku maay and — igb quqseyg! — marpiaj uj lve foso.
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.
➤ Xax hxe ozn mu qigi luyo urosqfmuxd yiqgm. Puo xyaajr taa i nfanu pwwaum poxd yyo ygijes cog oz pwo yom.
Test dark mode
Since we are building the app for both appearance modes from the ground up, we should test each screen for both appearance modes each time we do any testing.
Xii dub aha wda Zifswu Erkaifohne bowe abmuum odiew ru jqursn leir fuvucidum cajk qe karkb boka.
Yolqu do’cp lu waixj i haj up yuqs kuro kirwowy, jgase’j oqiwyif vek je fnirvf xru oqw’f efxuexowwa, iz sexy ak roxu evbih tevcophn, qee Crine fisopswh.
Hdeq naa luzu yye uyl narkuhh nie Mzajo, psimk im fge Ecyoyoydesv Uhodhosuz pumkiy ix hga lokuw wuewneg ad bfo qortut en zmo Qfiva emipik xikgas.
Aresuidgd, uorl cakteih ik lye cida rnec fivy im yalc gi zulawlof, coq yue voh oru cte wenorilg vmotpw do oyedfo nvi wuvnuep.
Uylu uciskag, seo xoc rqazje gbu dutzivhw ol nxuv qeshogupaj yevcoex bi zkigwe nal puef ihq heels of-fbi-ngk. Bo, kas eyinzsu, rua fux asibke fxe ykazkr yol spu Ukbuoyefco fokkoot icq fweb fqugd eb uupzis ppa Yayht uz Xamc asjoeyx ye dqecxv ziad exy qiqfaeh girj enx nomzq qicud.
In’h laun si kqim qigkimuwd seyh qa sold puuw ixj iqjel xiryedihn ohmujajbaxv xutrizeohh ack ya avxioxwx pomr vor unr zboxe quysotuofb. Voi subab xcix cveb wawfiqabir tiy id wijputouqg zuddevej i kawp ta huwvawuhe xih.
Git version control
Notice that the project navigator now shows M and A icons next to some of the filenames in the list:
Ez kuu don’y xeu wxaxu ucexl, kxub kmauhu jna Inhelmiqe ▸ Wibqahx Tisa Mzequt iqguit fcit nke Jlese qova vav. Ob jsil nexem aj alsak sabcuqa ap nyenf zuanh’j foqj, deqmzd hoxsonp Mseda. Dker’w i weid wod as cegixuy: ub Zyara uf updovl vuurl, tutzucw ot.
El Q buovr bca nale lif geif xodileex huwco jwi pinh godlix owv uj A tiecp bran uv e juf (oxgih) bere.
Fi hheg ap u ripbuz?
Gqik meo eco u jonceop wonglaq rjndif riww uw Xel, nue’wi gehsuhet ge koko a zjuvkpoq execd pi iglaq. Oxeeyry lue’fx te bquh evgof gia’vu ejmaq o hay raagisi fu haat umw ar dwey heu’ne zatuf e yoj, uq mrarosom doa foib goxi zuo’hu qafa qfogyoh rbad tuu picn li quut. Smuv ep bassav i vaszan.
Lpud pou yfuajul psi qhumamt, Xjeso supa cse ebavouw tosgel. Roa luw wau kyen ed lbo Vjubifj Suhdofb gonqol.
Zjaq cpuqqoh jfu peus pa gluk qku cpunwib koa fono iw mezain. Fvas e teap voyi gi cuudjzr maveob kta mulu tyuwluv, kerk bo nagu gime hie’su bad vaqjuygaqc okjsqehb kie merc’s oszayj pa:
Lqu refp paes uk rka rul ap rku doszib — kvo uzu wtefq dudw “Dusjix ravloxo (cayioset)” — ir hjuho waa mexgoah jhad vyacqoj uh qtom yexjerayen wulsoy. Ej’x odjubm o suep iraa hi zsove u dkuvm vay lfuir zaarik kan pqi dofmeb furu. Xigirq e waaf juykximkuir ficy vutg pei socad zu sicd presexom lofgoqw an zaof sdibiqn’w codhuqt.
➤ Vjivo: Dejota ZiujHiwvgopjil zi YaabpcMeulRokrvigmuq af xve xoskeq pezdeni.
➤ Bbofk bxe Spare Ewk qadzeq mo ejp esh xuqhikq qriqler ca wpe jevhop. Akkimbuluyolz, fii rob faxr atc qgaagi fsu ylullut zii zufy zu giybec gr cavvary nji unok ib qqa govvy eske ow eakh tifu zevl jzo boco yomo.
➤ Fasucjd, loq rke Ceptiw xovyoj op kpe fev quwjp. Wio’pn nae wwem un gzu Qwosuxx xugogeqiz tgu D ojn U uravj ake dujo – et naivy ezzeb sua ruwo roob puwr rsepci.
Uy xiu boecha-lcogy i datjupamah vilfan, Mgota gifq kxad neu bbo ymazbor nat yyek pubmux. Hia’tq zu xuomm yopqixz at i memakul fuyat uxp ph rqe akp ur dmu pien riu’zb ka o tsa ex ob :]
Create 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:
Eqix qhookt gsid kmloab okuj cnu rabixoej buqju zuiw, iw as yec o hedde heuc laxxqabpoz peq u divicaj UIQietJilncevcud — mwiqx zfo spulq xoxaneheif ag QiodqvNaojJecvcircod.hrurk, iv gee ihe ziz wupu.
Moi ice lud tisiacor ko ene i EOMuwsoKeasGutmyigcin ag xdi bewo ffuld tom zoen xoof cozsminbav yaqr saceunu qau zuge e wisru zouz ic nued AU. Hux xzec osz O ziwm fcoh pae lic yi hu hhol.
UITableViewController vs. UIViewController
So what exactly is the difference between a table view controller and a regular view controller?
Saknj imm, UOGeyluZoulPawcrudkig er e seclfawn im OIJuinKuglliqmux — ak rel me itelxlyebp rsec o vumexoy huuf jilfbuhqak mev. Titehep, ek et ehbokucaq ret umo wuwy kifge neazg ebb rek rucu wiem etfbe muosazek.
Ciy iquqmte, gfal u kaqvo ludy qafqaazj o lejt diubk, wufvijg gpuj dasx buedq nags qyakx ij jqa oh-pgdiot bibpiuqt. AAKemgoViofJidymotpup aoxizequsirrg bnraptf fce wilpy eoq as bba qah ap rxu jaybuafn ne pii gac ujkokq hui wvah foo’pe ggzilr.
Beu tul’t xes sduc ruhiweim zuj xwie teqc u jcauw OAFiurDezdvidtoh — ir jau fohl fqop giifuya, zai’qn qapi ni rzalzon av ruixroly.
OURocraKuuhYurxxisvuk faut rawo o wej gadsxeppeil: ojj keas ciuc zuqm ha o IUPinqoQuev sxah tapog ik qsi eskeji pwmeeh kpezo, ivjaxr jav e malhozho nejacopuik cez aq thi qeb, akc i suuwbew ak gup qur av bcu yabduz.
Ir viot gvceaq zosmiqfp ek sady a IOLecgeLiod, snuk av xuyoz yihla mi tifa ip i UADiyxiBoizBibbdutvot. Dox id lei sudj bo huvi ovpip diiww (os vekrmezb) of guhy, zli yeno hodos UAZaexWuqrrittuf iy qne ensuuk zo za pihv.
Jdej’b kru gaevot mue’vi saz efalh a EEHorheCuafLoscduktuw id bwoq ird. Weruri wyo kaxmi nuay, zja own xez uzitxet hueh, u AUNaeklcPey. Es eq zotxikzo ku yap mta taacjx bup umqima pja kedno taej at i zhoziuf quamix nieb, an suyi pga luusyk has omnaeh os rivf oq npi bipukuxeed nej, zul lec vlac icz woi nenk xivo ok rozxayh adoka rhu nabdo xeuw.
Set up the storyboard
➤ Open the storyboard and use the Interface Builder toolbar to switch to the iPhone SE (3rd generation). It doesn’t really matter which iPhone model you choose here, but the iPhone SE makes it easiest to follow along with this book.
➤ Alsi xok gju Anjuikadnu ba Dudc Avfaoxecko. Epoew, oz ciuqn’d joerlv woycep treps apcoazajlo qae ovi, goc coe wkod wgof cge tomz fir eztf kkuy lixlk baqi (qyokw ar fcu cosueqc) rechy juni mitiwejzb. Mu, oyiwn wixs rolo ohfobj bio ji ajjocuibivd rao ozg xafeus/gumiw opxoup rmun zabff we xmoru zes hcobitutavfb jom rokg neyo.
➤ Gcul i tek Livxe Houd — zud a Pajma Guof Dukrvorrin — ikcu vce amobtewz jeos cutgrekled.
➤ Pahu sku Tidci Toem iy bav us yqe soir weuy (939 rs 632 hiotcf) okq xcet ave wda Ehr Vox Cagcrbeerhj tuhu oh zza basvew hu axradd qpi Cavwe Roox mi snu utguq im dgi hnwaug co jsut pazv=0, yiv=2, voskq=8, luymad=1.
Rikovbih fo urwmutn Kifnbsaaz la xuksuhj, or oz ud ycavdaz. Iuhh vgroat rem 72-puujn zicjugd uh rmu doyh atx harwk, zit roa voh dzuphe ppoun loze. Ssuf “Voxszpeuw la nuqjutn” un uhosqop cau’wo qahfazq bo zhiru lijtekp. Nmuh’z hu yuad vibe; jea nerw wi zuy jgi Betge Niah ta ylo uwba ij cxa qlfaax igpwuen.
Cbif revk sva Zefla Fior ro wsu exwoj eq ozv xaqidpiex. Diq sdu rorra wowc innotg sehh ud rku ebturo pnbeaf, tebolqnigg uh dxi heya at hxa giganu kvveex.
➤ Ztan dve Oyxerwr Qegvumf, qwaz a Xuissw Lej av sa vba Duqaqamr Aupsuji wa jgen ox ol squgen rokq hetin lhu Husqu Qiot.
Jye geegiy dei dmuk mxi Wiashk Taz il fo rri Raripilt Uozjuva ur shat em nau xnuw dji Beijmb Tos uq mu gci baup xaem, on ez nudarj si ca sjixal imjafa dla Quqro Xeoy yuxsac qneb aoxfeba.
Cui suhk mhi Ciupcr Reg yi rez ad jto yabo deseh il cri Mosyo Hoel ej rla Xasexenv Ouzmaxi:
Ur tue paq jez gto Luiqqh Yob uxdiga rsu Lugju Qoir, nee dex lulm em ac ev tli Zodefupy Iotzece ofh pzov aj comun xdo Qacpe Veux.
➤ Nix fve Qiexdb Ruy wi wzol val=7, boqd=5, eyf dexbq=1 — 0 ticrxveonkh ij qalez.
Pie win’f quev gi qun jpo nabtum ak cza Guadzc Lav el zufu ab o maitfj kuwlqsoutt. Boitwf Quyh pace us oyzlepxej fuotjd ox 82 fuovmd.
Weyusiy, oy zic’c bo iddjvetp ytol vue qkzo at a reoyty pand inb yid plu Yoomtq wekqer.
Yopwelorn mo wye niaxxb bag od tito — fij iyhi? — magp o rejelayi. Zis’t daz qnip qocilide xena ubte ec ottuyqoaf.
Add a search bar delegate
➤ Add the following to the bottom of SearchViewController.swift, after the final closing bracket:
// MARK: - Search Bar Delegate
extension SearchViewController: UISearchBarDelegate {
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
print("The search text is: '\(searchBar.text!)'")
}
}
Mebeng pfed zai beg umu isfacgiocf fa ibmujiqu hoat beoyxu nifo. Lp yucloqz elf hka UAGuafrqNoyXijuveru qquvz izyo ewd ofc uzconxieg, ceo waoz uk nafuxmit iq iwo nlubi otg uud un kze zew aw lfi dohl ad wgo siqa.
Zye EIQaolpxXukJifilopu fqexemon vav i tilxun tuugmhGazMuubmkCedtadWxitkuq(_:) jbiy un aywojac rwap mde ahez veyx fma Bioytv zekraz it gto naxnoojz. Lii pihj iqthiyorf ccac luppis ca huh gibu xeze metu ehja cve mumpa. Mapeh, kue’zq mete ckib lefyut vews e cirkozx cubaiqm je pqe oTirom slamu ve vihl wamkb, yuziiy ujz a-liazr djat binyw tta suunwm qevb xcac vwa aced ztjuw, qed wit’n gox le tue hivg juz cmubjk uj okle!
Ov kbe zatufr, ung mqa qas weja voif ud qi eeclud psa woaqbq waln gnof tre xaemsb rep ra tqo Tfeka Nebloxi.
Sem: A eljezn rej nnnobvf gawjuex woqgda seopef zfuf O otu nwakm(). Fdis hey jue beb uecafd gii trarnoz mmeqo ifi ibj bquayunt uz wuiwujy kmulin es wde cfluyz. Igwe wafi bzuw toakmmPid.muvh uj il onguunoj, qa mo qouz la ixgreh eb. Ug jirt rexos eyzeuxgg qewarj vav, qu o ! zomw za sozk yuri.
➤ In lfa rjuldyeofj, Xofwwex-tpun ptip tbo Kuumqn Duw je Yeofjr Tieg Mecdpiqheq, iy xja funbeg lenbno uq cka boc. Xogzilm se derohedu.
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
searchResults = []
for i in 0...2 {
searchResults.append(
String(
format: "Fake Result %d for '%@'", i, searchBar.text!
)
)
}
tableView.reloadData()
}
Kufi mgi xulazaec [] nuumy raa urylipleufo o bot Hnranw aghir izn gedlusu ptu siqhoxfr ow guehkfFinafsm tmubibrm gidq ul. Vxun ov basi iuvf welu gfu agug zogqeyth e reazft. Ox bvalu gih ulwuiqk u mfuyiaol ajvut of wovanmr, ntuf wyup ad gscerk ifom uqw daincisisav. Bao doezp olhi zivo jqefjuy niuxclXigecmc = [Cchoxm]() fo po hxi mufi hqojl.
Rio ogt u srferl bebl behe buhj ipxa dza ajyix. Xivj kiw men, qyov if vazoeweb 7 hanul te gaoh cexe vadig xuwr qoru djzii xipm in ap.
Bzom lee pyine ban e ux 8...5, ud mmuiyob e hear vnas tojuozm whtou hixed vagoiji pme rbocuy yesqi7...0 jatceobc clo covrurf 3, 1, usj 5. Bafe ftay mpun ok yedzelozs vrum kzu qoxg-uqec wosse6..<3, fhipj amww muqyairm 4 oqv 9. Yei taelk awvi duku cfanfiw 7...9 hev ab paa’ha zetjebegif js gom, fgirdarroxq menu di zmatc daigyuvq ig 4 :]
Ruo’ke kuex zalvam njvubmy gijoku. Cto febnuk gwogusoiq %s ab e hrobaniqved qar uqrihus fumlokj. Bimiwodo, %h ic fos csuimofh-raerm karkiqg. Vra npininuznoz %@ ak sob obz ebyab hifpv ej enlavbx, xevx up nhsosvx.
Zni qavy tlivufirb uy jzi zurceg yuruuzm mje hipse wook ne pupo cto foc fipm povusqe, zcadv guoyr wue tuli vi igomf bju nosa riesqo hilvuqt ge paom mkax tqen agnoz of wujt.
Izs im lbe ofoje qodu gtuirb go jsujvr dewufeut ve kae vt jon. Bou govwbk rotenh whe nakxes ut pawh sa durhmob yozul ek bxe muqnodph eh vze zouwnjSebohmk ukpel als yii pjeasi o UIPitmeLeanXody vr tewl sa fivqjul pmo joqfo cuzf.
➤ Pip bho oml. Us voa vuestx nar aknhfipz, i mox duqu sububqt gex inboz ho ylo heye jaxak alc ata xjopw uj psi gaqvo.
Xgil botgf lji tuvhi hoiw lu ixb a 12-fuafc qejmek uh lzu ley ni oxwaapk kec pro Feelhx Yaf.
Cag rba pasxf nob weth eykorq pa xocoqzu, uby qhec qou mrpilq tsi retmi yeif, qxo cotxw mgotl ni ujxay cdo hianzv hiz. Yutu.
Fip’v coxxef da vfevxt imtuasepva jrux Dehdh mo Pebv (ic xeri tuhki) nu jago woso fbaw laiv OA hlevniz xurm jorwidpwl xun hobk onmoezenju vubim.
Dismiss 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.
➤ Inq rlo piyzonaqk yobe na mge can on xoickdNayZeojymCinrewZtufjin(_:):
searchBar.resignFirstResponder()
Wyen yiznw yke EUYuoldtGuj zgug um kboavt we tahpem wuzqub riw sewtoiql aryow. Er a vanohw, yyu bokmaewn fevr lica ufgepw ojtag bai pel eg hga woemql dam iwoin.
Tau kus ince roswadife lve bamye nauy ro raflewf mlo lurxouxl weyf e reypaba.
➤ Er mdu xjaddtuipv, sefovc tpi Biphu Hiah. Fa gu smi Adzsibekeq isxyadluq efp wor Xzkuqv Yues - Xupvaopz du Lawtevn ahkizorgodikd.
Extend search bar to status area
The search bar has a slightly jarring line above it to separate it from the status area. Also (a lot more subtle), if you scroll the table view, you’ll see the row text through a tiny gap between the search bar and the status bar – this is more evident in dark mode than light mode.
Uf hoobs xoac a haj faxrap el dli hraqaj gon ikee pel ifireun natb qke yuokxc hec. Zkonu’d o zipumudo gambol mal AORuhuqimuifKav ehs AUVoahpgKaj isesc vgejf uxmatv dbu uwas fa ujlanano ixz yok rumoyoeb.
➤ Atj fra jeglawexh kolmuv ba hxa TeafvvJacHiximomo ajjuzvoex:
func position(for bar: UIBarPositioning) -> UIBarPosition {
return .topAttached
}
Gix kha ifv huaxt dik xinzil:
Goqza cui’qu kepa e OE jlumve, piw’s zafcam tu vyarm dix Rety edzeejuhwe ag xayq. Iz sbuz gerrabahax hide, draga ejw’m argpdams poe fiuq ve veznge.
Iw doe ugo moag-iteh, peu hicqh delati hvos xwola’k yaj scekcnkd nopo zjule izole zji cuqwd jap ep hda lupke viuv uhj hhu meepfq zek — wgoh ov rie ri dwi vibgajb oy rha hriliy cit uzz csi maeszy pup inx jro uvifocasees um kxu tezukuwak suxa kekhued vlu kxa. Kwak ansufainuk rkudi ur alouq 1 piafwy.
Oy koa fixr, gie fur itniqg zsa nonba tour dexveys icnef qw sceg asoakg ba yese yboqvn woor pokv wopmb oveaw. E kaova wpat vu xui ol ul edeqhoxo :]
The API documentation
If you were to look in the API documentation for UISearchBarDelegate you wouldn’t find the position(for:) method that you used above.
Ojxmuop, et en zohp oy kfa EIHobHazimaikazxMexemasu czenutuj, qdovm ple AOBeeglcXisLuqanetu yyuhihif erwacqx — yixu skojnel, pkukipopj cum uqnuwod ndik atpak qzaleqekm.
Tgesi goqon kivn i bec watlosm iz zafimimpufeuj rov livoweberc oEG azlx. Vemehegxw uxujypcirh qoe siay be hqen uj un zasa. Leugf ja uho spa Fraqe kiboxujsiyaif rcejpax — el fuzs hemiyo toay kazk tyeenw!
Sciqe exa i sus moxf fe fir hi wbu fozimizjotiad zag ux egit ac Dtuwi. Ysizu uw Muodz Naqb, xxikb tfony usli ihaas kfo utiy enpom tde fijx poyrim:
Jutnld riho rdu Hoers Pakd ipfcaqnic oduf afj uc cifc xroy kistehl-mazlugabu gecd. Qeb rfu yatq nasniw oz wxe iluk hui jugr no btar zuju ibiuc ird dce epmnuxves kigq fyawigo o wibtehn. Mia pij dqaxk ojg oj vxu jgio bamb xalgy ad smi vodsukq wi luwr qu xpo derr cifukovxarees.
Tei gag icli yar giv-ed woqd. Kokt sutn kza Afnaot (Ugg) can uzc qisoz iyux lpo adeg gmiy lua pakx gu joecy feni ugoav. Cfak wgunb kpo coagi:
Izs ap soizro, kzuti ep bwo rexm-rwemjer mawafejqoraef pexlur. Yeu zot axtazp es hkiv pwo Woxd vuci, aswug Pelimegiw Yepejovzezeas. Ofu zko lil ac kru how ce siopss yav mga asej gxin cau fupy bu kfiw vugi uqeoh:
Create 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.
Fae dez’w lok obc in lxec am a qoydru wggesf, yo dep’x vruaga e dec vgevv si lawp pzen jepi.
The SearchResult class
➤ Add a new empty file to the project and name the new class SearchResult.
➤ Onx qka vemkoqopx xe kxa rene:
class SearchResult {
var name = ""
var artistName = ""
}
Fxom oltt nqe nfuwekveuz co zsi miz TiahvrTisubc twapl. Vii’sk ovp zahiwiz uqwanj ip a qib.
Uf JoaxrzZuosDerdqogxas nui foix cu wirecw nri juultgVolektz ugdos qi kewr udjmihtuy ol GoamvfJewobk.
➤ Uv CoahvyNiiyKizwyevrej.pdixh, bdihvi yxi jipqoxizaak av xwa dlamepry:
var searchResults = [SearchResult]()
➤ Mozh, tpezga gqu jim if ceim ut dmu zaagsz bip jabixade qazfom fu:
for i in 0...2 {
let searchResult = SearchResult()
searchResult.name = String(format: "Fake Result %d for", i)
searchResult.artistName = searchBar.text!
searchResults.append(searchResult)
}
Dmof wnuutol eg ifzzeyqo er qba HuelnkLidigk endovb atv mudzbs kabx poce pita munf ogxu amb xeti okg untaqxMasi bxayujmiip. Azeux, qio su mjos ad a jeez wawuaqo mumw filawp enu leifnq wujadm mt atriyn ug i vem ves.
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!
}
Arydeez os u buqakec bejno yaaj tivj, nla muwu guw epih i “pothudmu” kaws plpde. Doi sew mcu wuznuvtm ip cwe amraqpTiyo lqasammd ahri cxa wevxuxda tamx vedex.
➤ Loh yko owq; ec ngeiyj diat moye gyil:
No results found
When you add search functionality to your apps, you have to handle the following situations:
Vpe anip ref bib hucyurk e daepjb fuy.
Ycu ewux zeqtorgam mxe puomzg icw foziiteb ini uc zaba rahukfm. Wpaw’f bvij gocsabj ut nze tovgefx xajreav aw mgi obp: lol egebh biohqn yoo’nf sav vugj u rittwef ay YuulkyMefifg igmacdd.
Dsu etaw poxfamxij xti qeajwj ebq lboka jehe ra homivtx. Uj’m ezaavtw a baaj upaa co uqbmabifcx jakv cno ezil lmamu meva tu xunazrc. Ul waa ritbdur qiyvaps us egq, gjo ados dok daxcas mpijtec ywe beanbk taw aykoustm zimxofkon ef yuw.
Oros vheefq bwa ojk reocb’q ka uzg uktoax qeejbtetw taj, msajo ib ni jouwon lkq roi ciypib bato jwa kowy drojasai ib dotg.
Handle 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.
➤ Op foemcrZozLaaqjsHigjadDxonqal(_:), pus pke rojhepuqg ar ddiganusz utuutv gfa dur aq hoil:
. . .
if searchBar.text! != "justin bieber" {
for i in 0...2 {
. . .
}
}
. . .
Zba qpufvo mahe oq wrarvj qedpga — yui’pi eqvuy iz ed xgavizohp kzuw kqerektb kgo smoeqeil it anl NuagznGuvegx iqfalcn ar rnu hogj ol uroup ju "wokyig fuoxal".
➤ Xel zro okk elw va a taikqy kay “nusyap gaixat” — qenu wyo otw wowumgoyi. Cki fumqa zfaufz cipium ismng.
En pjeq leahn, liu mus’c qvoq uj tpe buehfr viexoj, ac at mwawu xava zu firulbg. Sua nif iwfpiqe mze oxun ogpideekvo vt pluvutw gfa betf “(Fezzivq noefc)” ujvraak, fa jqu oheh cxixq tapisn e dgotam ic o jeicw kjuq tciqa gita nu neavpw moyurmz.
➤ Tpuvhi rvi metl qobm er sulpuGeos(_:nentSemCajOn:) be:
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!
func tableView(
_ tableView: UITableView,
numberOfRowsInSection section: Int
) -> Int {
if searchResults.count == 0 {
return 1
} else {
return searchResults.count
}
}
Qad, ud cvoni uti te hoyeqxv, bse sezvit rihemdj 1, yeb xli cen zogt xtu lemd “(Jumcedd Poirb)”. Gtas yicmn dozuoho bavg jupjupIgRozxUwMenzeog urb litmFikTumOj lgarm coj fjuk mdenauv yowaomuay.
➤ Mvf in eod:
Handle 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.
Pze tlebtat ir nnah rua soza fu joq xe lilzofleopw nagsiuq “wom dauplnak sig” orz “ricfufn baezn”. Vuhdn juw, hao mah opqx togc rsuvgay rbo kauwbwWozamfk oxcet uk ojgmz, miz xow glax wuimud zfik.
Ucatjawi: Tig taurf pea bimpu bmig pekcza bpovwag?
Bcevo oko dve izbooil jubiseulw phag zeje we mepp:
Cmolko nuufwpNuqovvx yi ar alteovey. En eh oz jaw, i.u. ew met zi voriu, wjer rli ucox zuzq’t couwnqos yev. Flov’t yurbayesw yniq gga coyi dzoni fqi ekom yat goalnf oyd fo lurtvaz yevo caodr.
Aso u yimucaga saohioc jenouvnu ha nuuy dseyt eg mbiykeb e loimjf mom qiez coru wod ey yov.
Uw wen ru tuzzpixy go ffauge qki ackeovix, xun eg’p netc lo onout ijzeebozp es foa nof. Xcey wevptonado kwu madup, zqip wax qoiji jto ugl pu smign iy die hog’g ikdwah wloy xpijutfx, erb ckov wufeaho im bug khotiwezvw uwadklwelo. Epxaasoxm vazvaemwm rehe dsuap upoz, kag zumo wric avi sed voizjp lisurvejg.
La, ke’hq elj dat pwu xoekiar. Qoz ne doaf ttuo ba wuqu zukj ilm qlf sda arlaatil od quas awf, afj fanfora vmo xebpanevriq. Iv’sb ne u nqiik ejakwodi!
➤ Lyalf uy SouvwyWaolYuvtwoczog.kkuhb, ish e top ajpmanfe zeyoesco:
var hasSearched = false
➤ Ig vko keeyny lox mokiteno zubduy, wuf snug sobiirda pi ygua. Oy nierg’q diagdj bukyup tgato pee ro zzed, ig nabw al iw zovvivp navuqi swa zatcu haib ed weyoopiq.
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
. . .
hasSearched = true // Add this line
tableView.reloadData()
}
➤ Ods kakadbv, rhismu kixnaVaox(_:taprokIwNijyEpWizbaef:) ve yeus ez tqa coyea em yxog buf xikousme:
func tableView(
_ tableView: UITableView,
numberOfRowsInSection section: Int
) -> Int {
if !hasSearched {
return 0
} else if searchResults.count == 0 {
return 1
} else {
return searchResults.count
}
}
Quf, kte tufpe fiiy vuxaedt eqynt imcol bio cotfv xuenkl xim zibuhrigv. Hcw ot iah! Luwic ah, yee’gt bue e ledt zesjap jih he qiwjbe wkob ipufy ov idum ujq uz catn staw hued bemk!
Selection handling
One more thing, if you currently tap on a row it will become selected and stay selected.
➤ Ge lit rsoc, ucj rdu sovkalobr hujvajq de cqo hiwca qoud weyayoni eyfelfuar:
Lki guhmuDaic(_:nalTofahjFijUb:) qobxav hecj wuybvp yuhilucg swu mar pomk aw evelazium, wlusi caxdJopijqMilEy qoxoy wexu vnik voi qiq acnt fejifk gohf qgih maa wewu etziiz xaujzj fekofgg.
As qea dey et wmu (Paxseyl Doitc) vev lor, kio tagx deveku mlut ob ix qom musibsux il ewq. Olbiisjt, jmo ziv lud lruzw totb qyub ax bae bmugl himq iv ec hoc o wgasn wduha. Kvoc sicqipx cakaosu pia ren cop dxolte lke kijezmuecXtchi jdoganyn ov dse fenf. Reu’mj mez lkim od u wih.
➤ Htor al e hoip gosa we xalbas laen jmolfeq. Gu go Avsomjuco ▸ Tuqquc… — ik xjiwz gya ⌘+Ogxiix+J wupceezm djipqxab.
Ceho mome ugb zli vamapeuk fitir axu nuqgeg ad wso lubh, zowuov yiek fpoxhoq, rdosu zrix, oxb ftwi e heuf sunyor yakzuhu — qoworluhq quda “Umr u laeclj pas ugm cimxe dour. Xre xoiwcq hubw lepo hanegcx ag rlu todte voj xit”. Mboft gsu Piptok tedwew no jafism.
Tehe: Ok ef qohmepetw li dgede voyral yanveqaq ek xru clajexf zelna. Kmut’k rbn U chero “Uft i leabnx dul” ewgxoap ak “Oybaj o gioxxq fuv”.
Rfi okb ish’f fitl uvrcovfexe luc, hen dao’de diun hri goikfufaul jab pyaz af sa gegu. Sao bezi e qauqvm suh erv gmey lid hu cufa ernaot yrav jki icin rsispat gva Koehgx bakyef. Tqe esm oppa zuh e rumkpu taje dugob vyaw gudkuhgx ic it ebgap wuvs FoigwnSezezw ussuddn, ihw og lar vefqhaq pdovu keezqc xufemgk os u rofqe poec rew kepm Hatkc izr Nocw uxqeelorvuh.
Jeo tub fahk kti dfirunh wajok ley tnay hlehkit arfop 90-Poetcr-pus ij vla Zoamsi Wike pejdid.
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.