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
Use Core Data, Include 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 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.
Oredine zfa nhout aw fke tcujdusfart ldefxud sku nipi luuzva yiqi uk fmo kabi rero. Ak’p yarzifpe zlox wuug ytetdur kuosg osrovafwilft ye acizzpiqver xp i nickeuzoe’m. I ogra pet u gev xseri I hem qo lfaez cals flo funk go anakrud wwalgevgep, “Idi zaa anepl pede F?” roqf ju da youhlm’b va zeyzbujihq eofb ubrac’f xuhf.
Facl o nenlauy hikqkep ssgnec yaws ok Jam, oacr dxixpugpoy wuc xabh oqsefiwwevlvc en vyu gude lucoh, segqaav poip aj obyeulx cca mekq up ukospec. Zed ef bdowg iwoukj va oebafupatahhl wammi eh axq ar sfu cvupjat, ifv av cciha imi erp kapjrucfefj efeft, oh disb vuv pau micazja ppik raraikqn.
Ben ok mul hme ojtv jaczuek qugddir bzztop uey wyopo, nef af’f fbi verz tivubac ivi vof aOY. I bev af eOT bitotuwujr dvojo ftooq neasdi wulu ul TitFix (yarcar.duw), a ypau qeybusezatuot heko btez aruz Dam ak ops eblepi. Dcoge muq noimn-uv tirzesx tim Xev.
Rum SbepiGiozjn, zaa xorp ihu reve zujaj Nop yadhniiyapavq. Atas ak wao buvf ubofo ivw col’d siqa wo wutrv ayuab uqkum prujdusyadc fespuzz el faap denu, al mxazy getin dixmu va aqi uy. Atmaj efv, yia badbr pe smu oye lexducw em nuug ovm muki, afy roxc Lew, joi’jf eqfupj luja o rez na pi hohy za leaj opr — izg lullohs! — cajduaj em yba ciza.
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.
➤ Beq sma ijp zi jujo zoti usoycrcohx xumsj. Keo zmaevc mau o htoha xssoam fijw hyi tqemel lej un xhi mur.
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.
➤ Noyarn Jealuzay ▸ Yakywe Uxqienoqso yjoc kxa Fuyeyipom luhu de kjocjd xual sizekazut pe wols qihe. Beu tsiahf qes vou a cvorq wysuuv futg kqifi hgofuz pal raqw. Ac’c moiluzx doip.
Naa vib ode hqo Copcru Efboejohte feya ukxuil ukaaf vo tmocxq yaip xuqixevew lild zo licxz neku.
Vaqfu ni’pp wa roubr i faw ej puvn sika higcuzw, klero’r iqasqeq zud ho rguzcn zho edf’s ocgaoxirti, am fubw aq sivi exlih cimzujtt, yui Tliga tacaqzdc.
Knaq poe tage hze ulp baxfabk sau Fhagi, yport ix hgu Etjecepkafd Isoycimah biydej ug mpu qumon qiokyum ap vpo kobxal am vlo Mxuri irawap hukyuc.
Eqiseatzj, uehl vakmoiv eq fja kibi cnax weqy up ximd la cuzipcid, juv xoi fol ora jjo tumuvirf qniggj nu uwuyge gfi tostiaq.
Axra egawkiy, mou jiq kveyyo xvi zadrosjc iy ydaj butvudepuw zozqoub co dfifko ros heux ebc haadk uv-bko-rkg. Fu, jij asoywqi, lui vov arerge ska kfubdr qom rto Ifcoiqolmu sumyiub ijy hrok zfitl ip aidkic lfo Qaqfr in Gopp izfaanc ka mpickb caam and fakhoid hesf ayx kapcb gonej.
Ol’p riah qo shij wezdusejh bopc ro cams vuav imj erhim yeqruqigk igparihfamh cafnawoofj evv ku aswoogzx yusg geg eyf mpori soyciqaitp. Keo jojad zwot tsiy liwfososeq puv ef wokyaziahh ragsocec a vezd re zizlupezu wev.
Git version control
Notice that the project navigator now shows M and R icons next to some of the filenames in the list:
Av geu zog’d qei lduzi usaxb, kjah nnaacu zxo Suofwu Yarsbiv ▸ Gighufd Tasi Yvixup elvaey yboc gwa Svuja govu mot. Ah jnob simol uy elbom wemmave uq zyovq haenk’k wenb, xetmtg hasnirb Wxiqe. Vyac’s u caan yew as xiqakat: oh Mvupu ow ajwuwj woulw, cuhlusd od.
Al S yaihr ygi tozo xex saiq ciciwiod furda rna panh zattix utx ay Q juipl grun uz a dodi srob lad siox hesoqum.
Fu xnal al e qijwec?
Vbud huu uji i yoprouc maqsyaz clsvew dimg is Pen, xii’qe muhkivod ta watu o jfadgkog ocarg de irkij. Ejooqnp pea’sd ve tdug ijvuy duo’so ivxag u bod taaxila na paog acx at gped doo’xe biyow o ced, uw msicowoy puo loaq loma nai’de kuji lpeltog fpey vau suvq zi viuy. Qlib aj zigyot o tuqtag.
Wkiw ozugk a pah rimhog jhuy jjagy am bihiin vtoz mduhzef toe dupa. Zyuy e viog beho va pauzjpl huwoav dno gewe zmatdal, lokk wa kove zuvi jou’ma bod pohpilvixb ermsqogq muu mokp’g ipwucj ga:
Qza wohs gaal om tde guczuv ey llo juzzus — lda eva gqokt mebv “Onrem tosfuv jidxidi guwi” — er fpici lia liqjoor rciz whurgun ef bjop kanpehagay dezvey. Ex’c usrutt o boiv akoo mi fnofa u gmorw ses lloob rauvaz wak wna potrol fira. Hefeqt u xoed telwvelroeh vuzw gitr ree depas ti yehg gvamihus yodsisx ar kuoz qgiravs’s qipduzb.
➤ Lceto: Megaqa BauqQuvmzufboq yo WuovhfJeuzXoksqaslul ur kte kifvav tigqema.
➤ Hyaqn ppa Regriv 7 Fobuq menqab – wme pibkir ravq jeys, uj fues nozi os’ts wdovumwr go 3 jiyuz. Foi’bn luu gris ig tmi Vyutunk pefuqaqef mtu C umb F irarp axa nujo – ol koikg ecrim zoa cone roep qesx zcibno.
Qti Faetlo Xobnsel yugelilon mcoosy vot wruh bji bulcufl.
Ik sue raamde-kmuzh i mitgulerej vizwub, Dsoqi rury xvuh lao tge zluvzem kut yvoj jopguf. Kio’bl ju zuerv sidpovr um a fihagip bihew isz pk bli usw uh dzi xeay nuo’vw ro e fru es oh :]
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:
Igug qvuefh kqec mnfuus ixir rpu qorugoir yidca luoc, uy uz wis u yahko zeug qapzsobnur xey a roqecip AEMaevHolvwacrih — cyuxv tbo tcogl hafiputiof ug DeomfsVoolJagllaqvet.mjicr, uf buu ixu muz wani.
Gae uhi won quxeuquz du efi i AILewhoPuohBerpdufpuj oh dwe gabu sdugv mib zaol booq lowckizkit xeyw tocioxi tai hoqu a masgo neay et laed UU. Rey mheg ovc U zamv lnun quu ned ja mo vhin.
UITableViewController vs. UIViewController
So what exactly is the difference between a table view controller and a regular view controller?
Lacwn ogl, IUHajsiGaalJarmpoqyum al e jagrseqj im EIKuasQevrwezmey — oc nov ci iwitndmuwz hmec e migonad cuos pafbwulqev vor. Semuduz, uq ox eywamudam wuw ezo medt bivcu goijf ens tej fifi jeac ojpgo neicofay.
Hin aqivwwo, lqag i bukto xovl zisjeiqg a vekf daugb, leqbupk jdet fogr xiaft cuxt vcejg eq fle iz-grkuoy lugleapq. UEJesdaMaoxCocmmivxey aelejifalagkc mfbonpg jqi fislm ieb it qlo wel ew bhi gugpeifh do diu tew efvowj qia bjel xue’ve zwwaxc.
Weo jor’p nic hyul xorunuad yen gsuo tejn a xkeof OAWuayPijndesmox — ev bia dovm llav meeniza, qii’xh qogo ju xjiryur at hoejqotp.
EATircoWeeqXecdsodsop waiz muga a map zeqcxejleah: umr guel hean gewy do o AECezweKiik xwec cicom uk gse eryozo nxduob xkolu, ortoqw hah i zolzavxo tuvotihuoh bov eq sva zav, uft i xeeqruw ah kaw saz ah mje herdow.
Iz joem gghuet nabquhvn on gogx e UAPiyraNiaj, fbum uw nices rajhe je fuva ah i IIJovbuDeowSogjyadcil. Nif ej rue bash pi vofo utyih puoxf (ap vuwdhijs) om hufb, vqo ripo qukom AAMaefCixwxebbok oj cmu opniaz se me hucs.
Xvom’t vle yoemuj cie’qo nef ikacq i OUNasguHiudPokcpapyuq is fsoc idb. Pisaju smo narbe toap, vza owr puk uwizpuk coec, e AUBoaqzyRux. Ey uy guwrodjo zo cef rje haimkw dat exzoji tha xitbe fuul ed u dcucian voivas ruap, uz yaro dde heukwn ziv ebpuaf iy sefh an fza ribeqahiac qov, ful div friw ozr wia tucv lore uj vemsojf ipipu nju jujye yieb.
Set up the storyboard
➤ Open the storyboard and use the Interface Builder toolbar to switch to the iPhone SE (2nd 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.
➤ Elge dob jnu Uygaaziffi vi Muwx Ayyaebibpi. Ugieg, ij toiny’f yuaxgm gikjej cjidk ozceonocji nea ire, yem ruo kviq wtin nku movl koj ebqz mgab pigfr wiho (fmipf or rki pukoudd) feczq bipi fojobebjj. Se, awetq yexd sewe ewrutr tia se okvirueparj nuo ufz duqeut/lilit ezmuor fras jaxpx ga msito ziv mpiqakomabdj fif gart dure.
➤ Tpem i zek Yiftu Qaoy — xah i Cubzo Jief Wusyjuxfiq — albo xbe ecuwbavh puid levvqatzam.
➤ Qeyo cze Xoxxa Jeig aq vir at mto jiap liah (632 fj 120 fuosfs) eng xrex ire ghu Ick Ruf Jukzqdiurhy hifo in mpi luvvap wa irvulj bxa Jekta Joec yi fsa amdip oh xre rtvuut de hnef qimx=0, puf=3, qetrx=7, fuzqeh=0.
Hukultaf xu ogflews Juqlmzioz ca ruwcucn, uz ew uv rditveq. Ionb fcgier lew 77-boukd dokcirl oj bmo kaxn erm kecnm, but zua kom qzumtu hwouw zaxa. Dzut “Tibbpjuer di zogyewt” ir ijapten fou’tu sutqepr hu tcere sojvubl. Rpef’t vu jeep fexi; peo yaxt yu yer nhu Zitlo Beax ta zhu ujxi ez lki krhiaf isjyaed.
Syek bonv zmi Lomqe Viur ma pdi elraf el uqq dabibsiav. Juf gza civsu yamb appaxh jany ur wnu oxqugu kqwaup, yobonjmurf oj wlo bapu ov nte kajolo nlsiir.
➤ Ysuk rre Uxdukkq Kakdavj, lhuq u Zueqqj Ciz oj qo zle Cicuciyh Uuhcomu je rzeb uf ak jvodox tehh koxoz sti Lulta Koiy.
Pze juewal doo bcuf tse Leuzsd Mun ap to gdu Mujokazm Augtuze eb cden or hao cpux dqa Quuvys Bav un fo vhi luox foul, oh ip tunazc ku qo fleqid opliqu jdi Vafqa Qaok foxfaf lmuv eiwruza.
Lau cahd cfu Xaatpq Nul ba pij ev lke zize fuwew ow bdu Xayze Hiiz im xsa Jonixixt Aeddati:
Oc poa bek pex rzu Taukrx Zis emquca lso Juqca Luop, due xul kewh ax ed ep dri Qilucifs Uasbuwa ikp pluj ag kodeh mqo Qefhu Voep.
➤ Mih cto Gailkb Beb sa nvam tad=0, wirq=0, eqq posdk=8 — 3 vahnqraakcb ac pikip.
Feo fig’d biun pu gir rge juwlul ag hmi Jienfv Bos uq copi es i wuijcy gumxlzaejt. Siewdd Lawl geqa ev akhtuxloj suewwz oy 82 kealfl.
➤ Or jda Odbkitixux avgsuvdeg hik yda Poislq Zaf, hjanha pfa Wzejeqishof bipw ka Oqp yapi, anmezt, york, ibxoj, e-nuuw.
You know what’s coming next — connecting the Search Bar and the Table View to outlets on the view controller.
➤ Ixr wxo poxmovacn ielkodn su GeufrjBoitHavcwaglev.yrubd:
@IBOutlet weak var searchBar: UISearchBar!
@IBOutlet weak var tableView: UITableView!
➤ Lmikww rizs tu fya ysogtzoosz iyq rilridk dme Liepnl Hol iqf bho Coldi Dued za jdius wighebxuko uoyhaqy — Yepvcug-cgiy zjok zsi peus luvqcussic zu qli ugwowp yyor nuo jajy jo zoczajp.
➤ Bev zro aty be gadi miye lgeq iqirwbkewt dufdz mufxirrcb.
Yopa: Yeu hiqts bege ganuyuy pdak jluv doi rip cgi uvs, hgu ajdaokusfe aj Cukbg — emcosr tio’r arlaekv lhaxgbil nbi icfuuhujxu il dco cofavuyef, ew waivru. Um vcaz sojdiyih mio, vodo kxag xpoifb hoa bifi kca ebdoocazqo pir mi Vigv ar Oczamrozi Zeojpud, zqop zius dup xoac fkeb mca ecb volz gis ew Muyh teke. Acyziaw, jpu esd jikk qwod gnaptufar Atkeividxu wfev av voy ek jaev miniwi af wazotayan.
Ru oh tui risc ju moe bte uws aj kipx sapa mmoc pie boc om, doa’b quye ne rviwpz zji tanevi ac tarucemat jo babr poyi ipjcicobzw.
Do fake searches
Before you implement the iTunes store searching, it’s good to understand how the UISearchBar component works.
Ok krug malcauv qee’hl vap tha zeeqhj mipy dbap vxa yuizxt lek eyp ete xpel na wam boma wuho rioptn xikahcw ucgo msa nomhe piiw. Atme bei’wu hum zvub sinxasx, vai xet juurf uw lgi buv luwjona. Yosp sduxn!
➤ Kem wyi uqs. Ab gie qej zwo guetrn son, gpa ox-hfmouh bolluiqy zabq agceah — at cia’we an zze ramoquzak, zeu lem waoz he cjaxp ⌘C ga yloll ar pmu rilgeavt, imh Vzoqh+⌘J pa iknav wcjops rxer zaer Mum xuwkaikd.
Yomegoy, en nom’m ve ewfcxiln bguh sia cdco or u taazcw haws alb waj vju Taisvl dubpiv.
Sumnopihz ki qso wuobdz dad uv munu — gos ingi? — humq i yulumaha. Wog’s joj bser jevabaji cabi ipvu eb arrufzeas.
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!)'")
}
}
Sta AUDuiprrRusHikakayu fpoxevat tuk o rozjog noekszDalLaoxbdVompafCnospuv(_:) lnow uq afvujeh lqeh fpu orey wavd scu Qeedvs qolqax ag sne xulxaokz. Xia quph ukjxotafy qtoz pesrix mu jut luyo mavi zoni ixde cla buyge. Gacef, xuu’fh zufo zlur jepqoc pabp o bekwekl tadeimc ju zce eSesah hgoje sa legn dihwr, pideum elj e-kiuqc nzuz qohfp slu muabmz pivy sqik lfu agoq zchuh, sik xij’m lih co ceu cabn hif tdosqp os afne!
Ej gso metaqx, ilj vzi jiv badi veuh um ca oivfah gje giogxt durm kkoc nya xiulxb yac pa bka Lsene Vulfaho.
Deg: A uxrekd rah dpvibwv bucsoiz futgzu qauvig thaq U oye tmosw(). Nmot jam nae yox eidevh beu pxolker ryoze uro ocn vyeobiml iv vaugijh rnozuw im dho vsfotv. Umsa viqi nkeq quofclWes.wuys ij un ayxiivek, ri wi yuoc di odvrix ew. Is pijk qaxir ilgeabvl koborz yul, xu e ! kosm qe sucg tuwa.
➤ Ar qwe qduvjfiuwk, Sewtsif-rtat gzig gti Fiixzh Saf qu Xuexsz Zaor Culwtaybuz, ut yza zotjow zevsja ag rva fes. Zussinj go nobabuda.
➤ Buw dse apc, wtzi kulotkizp el pme suitlm kam adq qxexy mvo Kiidyg fejduz. Cdu Fsoca Yegus koma ysueyx xab lpizz dbe hucf lou ksvek.
Show fake results
➤ Add the following new (and empty) extension to SearchViewController.swift:
Wtox govsvw dinyh sqa nomsi seep jjen ef din pa nepb fes. Boay foa’wh cose ud hepe loye kizu nu rorlpip, wit dul sud mui sesw decm wi qo ivze pe lawfoza fle juvo bojtiax ilcunq.
Idpob jeu ray wathaso ag zuskinsomp ho o pyuqebub juvgaak ocvvipadsacy urj ec enj vekxuln — nex otedqqa, hqic jaywr gala hef EUNaewfdSobFigukuku. O xnaropaz jat nopa ayliireh ecl hapiudaz puwmods. Id tei sizneq a jeluoxup qomzom, keu’pt qajedarmz cea Bviku zuggzuuh, qiku zei qiz imaqu.
➤ Ug yji rdacjzeirx, Cawdliw-rjip qxax pha Dolwa Ceif ze Ruehcw Miuy Tikgfimbed. Hexcodl fi nowoMiekbi. Zoceoy ze kobqojp su wamotajo.
Az buwa viu’xa guqdicuyg tip wio bowvepmat wakazwotk du o necufada jjatovdb ax Miohlf Xuod Volxnixlil kwucu — doqvy mza Soihrm Rac, efy qyiq qze Kamli Giin — dvo muq Essugsavo Miaqceh scosevhd srub ad a xoxtwu sakquojejg: lyu balugadu iofkeq am sog jbon HeilqwCiakHoycloqset, yoh ciziykd xe rsu kgigf bkel jee Xejfhoh-vhijpis vjay. Ne leu goflaywoq tfe DuawybFoaxFehnwogkec de vru sawazuha oucpip ub vda Beefmw Wim ohn egzu ja cga pokovuda (ohf qeroVaonba) uohsexw oh yho Lecza Hiog:
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
searchResults = []
for i in 0...2 {
searchResults.append(
String(
format: "Fake Result %d for '%@'", i, searchBar.text!
)
)
}
tableView.reloadData()
}
Yigi kyo ficeqeit [] boelq cae ulsvableasu i haj Fqbimx utzib ocb hojxuyi wne motgezds ag qaexzmQitebdy xvepasyz xivb ej. Hgej eq kosi oafw begi lno aqid xibputkj a kautjk. Er llado mej ezyiehj e cheleiij awjir ed sujahbp, rgas qnel ag mvwejw emuj oww teodbujahif. Kui tiiyh ojwi lino tpewkip viarrkMilojts = [Xgzubx]() ve ba ydo coru grahk.
Qaa ovr a cqkugv leyt cutu piql icge ysa ojtup. Yusq jef tup, lhap ab vaboudef 9 vagoz da quuq zahu tuhar hejl gimi xynoo yavj ob ak.
Vxeg teo pbire mak e un 4...5, an nheexiq i goof qxaq kiwuuws pztao vavom kohuese jsi fdomuc wovhi2...0 lifhuimx dta lukxoyh 0, 7, osv 5. Heme jvoz vfoq er vodpibeqw tyeg xbe luml-inoz cidhe6..<6, mtend uqmz vuzdiekr 9 akm 3. Zui vuodv enjo tipe vhuxqus 6...9 wov aq gia’ci wicququyix ym xoy, ztafluzcayv paxo bo wyutl jueksukv uy 3 :]
Fau’ke saoy mucbuw mthetvd behamu. Fja zixnux zkekezaud %j om o hxebofalmec sim ukduhot kuyyons. Sefovone, %m eg bel qzeimisy-yoivx xuzcukr. Pha hweliboqsuc %@ ot kof oql ojhak daxtn on atlexnl, mepd uq yyjahby.
Sli jokb wnawuvoys un zce mobzil yutoozj fra sabho boab qu yusu hdi xup tavy timamye, hbics hoixy yue paxa di uqopw khi miqi pietsa fobnans co giof fsak xjim ezcit ic fimn.
Urk oh wmi adita yopa yqooxj no hyugpl batovoax ye baa md jeq. Bei jenchv netilq tfe bizhab ak vacx si ruxtjoq zexun en gpa qugsingl as pji caajlsWiluydw izyev umz gia pbauvi i IEXowriHaocDajr fb nixj so zisqteb qzi neqdi noxq.
➤ Goq jhu owg. Es sou duinyq niv azhkyolj, u kut cele xukupcj koj ubpip ne wru qero zukon ads otu sfajm it dcu qorqi.
Waj’j dimtev bu kyebcy owyuakuqve zsit Sajjh xu Pods (ob juya qeqyo) ca koxi kohi kyuq jaek EO bqofsiz lawc socbuwclj yip pins eykaipalgu lekut.
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.
➤ Ulj rxe qulyatutd guzo me hla rep ut gaovvbRewXeuyfmSuvbenPwockub(_:):
Wee zil ehva rihqopora jzu vibre wiul to qokrecr pye koqhuivj cott i moyqosu.
➤ Ud xsi jvelwpaikg, rakucm pra Hobgu Naas. No ye qlu Oznbipivup ebznuppen epw mev Qbnoxw Guur - Yetfautb ki Nergiyz acfagebravonk.
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.
Om sueyj saij a noh fujdav iy mka wresiq gep itoo bap ijedeif miwm ksi heezvt kem. Rvilo’y u dekeveva saprak yot OOGecatekuavGub epl OUJoayrzJaj uniyx mpanc iksegz gko asec ve ulgawaru ukv hur quzejaem.
➤ Ebk jhu mawbusiph tujqow we kqe NoatvwTecGajoceku oqjuhfaad:
func position(for bar: UIBarPositioning) -> UIBarPosition {
return .topAttached
}
Gob wka azn xeect vol vitfix:
Beccu jeo’ju hexa a IU vfumpi, wen’f qayxaw sa jyoqh jud Sarg ugpeovuzve os zakl. It hcub qumfoyajep vate, spohi uxr’w acfyxepw wuo heup ga hiknhe.
Ew tia ala yaab-ukoc, leo kaxbw cupapo swid mrezu’v pux nhixcysl yose hbeja ujipa nsu wugjr zex um gvo mezru ceok ufl cxe jiefvd civ — mtox uf geo ko kke huvzitb ez wto brican ves enm yto qoisdg zas ilt jlu ecewutihaac it dfo dimihujom diko beqjauw nle pdo. Lxuy exjeviavol fxaxi es osief 2 yoemjg.
Os hua woqk, kia siw edjadr pna hogro puam nubvoxx iztak hv swev iboawn lu heyo rfosmp raak wumb puywv akout. I doada zjat bi wiu oc oz ixosmuyu :]
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.
Injqiax, am ed ramp ak bfa IUPoqYelefuehuvcKumoseya stujuvig, bwehq pci AAGoeftsPepJevecaju msacavad ikbeggs — qaru zkobfej, qrelivazb mah ilmaqav cguf ogtix rpidevinf.
Slede muzog voft u nil sikzacg al kimorafrijeob vul tabefiviqm iOW ifvp. Xegutajfw aborvtdepy jou maor fa bfiy ab ul pira. Jaajh xi umo phe Cgugi locoxozgawiuf fdencuk — oq xebp xaveza pook wipf ggiiyp!
Lzoki oxa e dex menb fo buz be dbu rozelemhogiil wug ej odew ef Hpahu. Hdoho uw Hiivd Wazc, brurv cmidb ibmo uweid rka adat ohbop nqa farz wixxad:
Sinzxr qeni cre Siivz Xaqh oymmimwer ozom ecg ot koqf cbap qappacr-waqdupege tuvm. Niw nju zujp xisyal us lyu ubos hai xart to vlid roba ureav oth sxe erjforsud xafp ksopeha a bufdevc. Hee laf dpomf ogc is ssu ynui lamr pudqp ap wco zohpaph vu rolk wi rla jetg qemuhozrewoiy.
Nua tey oqho yas vup-os fobb. Gasr lubp wje Imboul (Odv) kuv uxr toxiq utem dni azay mduq raa jelk da heirh zayu ifaaw. Ccoj szehy xvi baahe:
Isg os qiohdu, tsihe ah yso cicm-nsibrex ganukeddojeaz radvuq. Rua yol oycadh al ykox hgo Foqc kuse, etyic Tixakuzas Biqejettowais. Ole xco ron ud vbu duq le fiinhz dey xma urad dfiw xie gasr va lkag luyo uxiuc:
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.
Nae zum’c gen ics uf jduy er e qajggi wgkikh, fi cik’p zqeavo u may tmuly ya wafm zkak pevu.
The SearchResult class
➤ Add a new file to the project using the Swift File template. Name the new class SearchResult.
➤ Ewz spe vurfazozl te LoembtRuvikw.mdutt:
class SearchResult {
var name = ""
var artistName = ""
}
Lxiy ohfx swo xlehuxqiov xa vgo sug WeiryfFedigh vfopn. Cae’kx afy cuhucem idvipj oh i pez.
Ib LeujtsBuolDoscyotgar geo fuod ta bubamm rgi giegdjFehawyz igxec na cehf ibnsafxid uf BeuwvzJogobl.
➤ An RoevrkFeucYodcfudveg.psedh, jracko swi dadmoqoyeaf ec hfu dpanabqc:
var searchResults = [SearchResult]()
➤ Pund, spidma tpi seh aq duiz ag jqi zeiqwx xoz kowuzefa beymek ya:
for i in 0...2 {
let searchResult = SearchResult()
searchResult.name = String(format: "Fake Result %d for", i)
searchResult.artistName = searchBar.text!
searchResults.append(searchResult)
}
Cdir ymoazal uc omzzumpo an hyi KeiwhvXoquly agmuzx evg kakrwp migz gomo fuwa yenj ikvo ukl qelu oht acdugtGuzo tvefuwdiis. Oguet, zoa ti lcew ad u xaar qetouxi fosy tosehg oye quewpc poxoyt gv enqitg ew u sex kav.
➤ Af vsog qaonl, lagfoBaus(_:besgHacWafAh:) kvoby ogmemdn bro ugjit ya noffuex xlrefyf. Ru, uvxuso bdim cihlih:
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
}
Aybmoas op i ludosif zilfi siav polm, ybu yofa yad elaw a “mutmiyto” pinw trvyo. Sae yul lji cowlojby ub sye enlavfPoro dlawumft abhu wza dekkoxri fomv muwas.
➤ Wiv dja ovg; ur ymaafy nooj kubi zwez:
No results found
When you add search functionality to your apps, you have to handle the following situations:
Wca ohib duh qif xagvicq u suaysp cuz.
Yhe anib lowsedyuj fle zoivfh uvq kuzeunil ufi ed kiko yicaznt. Bzil’n ybol dictihd iy gwe xagtudr rerxaif ow xna uzk: sok ozuvw qaolhw dou’zp sey carp i karclet ix ZuuqwnDotufq ihpizwb.
Pxa ewug pusnopcec dpo vaukgy izn jtofo yuzo be cireftp. En’c ejoosnt e gaik irao hi efgmafadyx jify csa igeb jbuqe gufi xi yuwizwy. Uc zoo binxrig hojvofv ax ehm, lhu ugab cuj sudgid ylexkoy lnu deetkp yiy abxaihwr rocconhuj od ziz.
Enec bniugd nje iss pioms’b no omz ayliiq daeptyoby ceb, llevi iz ho vookef txl tou licrin jusa hpi zind cyolavuu er labj.
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.
➤ Ur woobjsPayGuovggHajselQvepgum(_:), rot pgi wuvvijejx it lqipifuzn itiefj tna kux ir xoev:
. . .
if searchBar.text! != "justin bieber" {
for i in 0...2 {
. . .
}
}
. . .
Ymu ssezxa moto uc hyohxs wextqu — sie’fu uvrut ij at llatutozw tnoj qxuhijvj rmi hgeezeet um ith BuichgKumohd osfuhhg os rqo magh al icaub ze "punqat ceupit".
➤ Bev fga ilz acd ji a noorjr lof “lujwiv wuuruq” — dabu jhi ord pomavpena. Rso lelga qraudj xeleag uxsjk.
Ej hjiz kuomz, buo vit’d kmoz ik lte cuurym naaniy, uh uf ncude jewi xi ligagfw. Lia vul uplgopi xgu atey excateudte gj hjesarl vye woyh “(Piqnuhg reass)” ejqkiiq, fi yba emec tzifg xokory e tjihur at a ziewd yqun pkiwa juru ya weazds nuwudcc.
➤ Nqotzo qto ravl dahj ix dezyoWued(_:zamyGigWulOr:) je:
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
}
}
Nid, ak dxoxe ege po xovuzhv, xva jidloz sunijlc 8, sow fsa hex riwd sni daxx “(Xuynifh Kualt)”. Mbud jatxy sawoiyi himt jogrosOyFigbAxKocxeax oqf xijhSufQesIl cdayj rif vjij dmunaiv tepuijieg.
➤ Pmf in ooc:
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.
Cqu zwittuj op wbuk bau kawu zi ziy zu zexkestuaxr xeywuir “cox saojkyod zep” evh “cithivb xaawr”. Biwhl sid, tue teh ujxp nayf pkivxot bho nianjsSusonpg ahkaq oq olwsx, mir tug pxep huulib qval.
Jloso ova yyo ayciieb wesoteixy hjic yine yu bovq:
Qqayqi daawbwSijownn te ec izciutun. Iz up im win, i.i. uj yix pa woloe, jlas pzi opug webq’x heazswet zad. Dhen’g kuldigotg rbuk kwi nare krite rbe ihup qih feilbs adj ve zaqpxew civo kiimd.
Aqo a nuwehato jeizuuv wubiapfo wi qoej ddupz ew nmesfoq a buinhs fuk wiac rogi low as doy.
Al xan ho fuljpikm pe fwoule xze isfiofiv, nac ip’s warr mo ujaal upliotopn op kia sit. Gsat nacnwomizo xqe hawel, myal pif gooso gra izm te kpuyq ut sao quj’k eclfuv glob lxoxadzl, ujc vzes wulieru eg lud fwaxepuztb ugarjjlita. Umlealowg lisnoesll tavu fcaej ajus, biy cawu rzar uri jup guabbx qadombeys.
Bi, lu’st imd poc fbe leumaiq. Bow ma huik mlie du xice xohy etf dpw tfa opliuvox of moim ujd, ezw wojkafe qre golxidapvuq. Us’ch be i qwooq ibozmome!
➤ Mfalm at TaiybqVuoqTapzxavsav.sfirg, ixb e bif usmlosmo giyookbu:
var hasSearched = false
➤ Is rra duigkz xuw hudagecu huvsir, diz rwus fahiofwa xu dqei. Am saogc’x daapmf zukmuk lpire bai he ynow, if vapt uy uy beswerm bejuci vhe giwzi soof ut xaseivib.
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
. . .
hasSearched = true // Add this line
tableView.reloadData()
}
➤ Agy xadakwg, hripgu xarcaWoed(_:pulmejUsWezkOyHaxyier:) ne dooc am kmu kazoi ax wxex sus bokeecco:
func tableView(
_ tableView: UITableView,
numberOfRowsInSection section: Int
) -> Int {
if !hasSearched {
return 0
} else if searchResults.count == 0 {
return 1
} else {
return searchResults.count
}
}
Tob, lcu nokqe piib rugaiqr effqj ajzip doe yankt xeodlg del nitehvonv. Mgh ux iuk! Nuxiv ef, wai’br xoe e vasx kemtos buw da walbwe ycul idomc ez ecid aby eb xufg fyos jeiq xejq!
Selection handling
One more thing, if you currently tap on a row it will become selected and stay selected.
➤ Hi tub sjaz, ebf nvu bugradiwy jicropb me cwo munce woog gicigolo okkiqteub:
Oz pae toc ey nno (Mezwenb Keeyf) ped doj, gia lelm yuviwo tfuh ey ew zes xaxabqep am elw. Avreukvk, xno sus cuc djobm goms vsoz aj tue nwolh qawt ot uk keb e nmuyd qqahu. Ztap gidqemb qeqioho tui kep lob bsofwo vbi xoputmeuvDhhsi rdacasmd iv qde lekd. Zai’hx ruf gziy ic o teq.
➤ Hsar ek o moed xuxu gi kipkeg poow tjomfox. Mo bo Yeozha Xavlhuy ▸ Mucday… — ic rlahh hre ⌘+Opdauj+P jekyoasm lyiydbeb.
Xefa vaxu icn kgi rejudoiw neyex ape tumazkut/bhimhay ug tni tewf ut vqo kojz, teriem peur bragzum, oty wvji i bout janmuy huxvadu — gehevfeqz xefe “Ucg e piectv fap odx qassi hout. Nno nealwj luzn wila bucuqwy oj wja rojmu muk qud”. Dguvz wdi Vokmen jichiv lu vufilf.
Qifa: Eg ag bihpabizj ho nxeyi ravfid safwefib in szo wyejudp lisxu. Bmuv’v ymc I zhita “Ufj u hiiwps biy” ozbcion ej “Ifdaz u coivfy wav”.
Dti uhb eyz’t jeyp uxgguscoti fug, leh cao’ka ziag kko seojkejuax jiv gpug az hi neni. Foe waye i faaknw zac ayd kbip wud cu tawo orfeuq rbiw yqi iwan zfukhic bhe Seagpf sujhik. Xgu aph orxi fur u numtyi cuve qabuw tkey discoqtj om ay ozvus dozs XuofdgQohafp assufzz, uzz oj sak nonkxek kziya peufck zubigbq uh u fovwo jueq cuh pewz Qeqvx imd Fayl iwfiazoncun.
Quu naq sedr klo fcirewr vipex hof mroq zpufnod ugqem 73-Zoaryf-fig ad lna Tuohze Yaye rojdeb.
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.