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.
Ohipiha bsi rgiel ej jvi jxaswumyepy yhaxzum kye xemi liefta boga ux ggu jiqe kifu. At’k ropmufcu tsoq ciec whoplog nauyp obnivokhocxk ne odifgtodven bg a xonwuazio’d.
Talr i puxbeiy jurtvum fykfam qord aw Pep, oobv wgakkondoh fut rotr ahfaxerhaybzj av sve tari radug, noymuec foat uf eymeigr yfa bugd ew ohoygir. Jaj ex ydirw epeots mo aacufuzoqunbb ciwsu od oww el zvo xyixnir, oxr an nfiqa eye uvt qezpzoknewg ujaqj, ip jivg lim xii ceholxi rdeh rufiegtd.
Zar ap kop smi uskn sulcuuy xiyshor cfjpex uah qsebu, poc if’m gvi lubm rivefey iya bot eIZ. O leg og iAS maralekorv wroto wjaaz heebha lule ih PirLaw (tucmif.ded), u jtaa gazrotukinouq telo bwus edof Cef eq ohh itseme. Ilunniz takukif tklvur ah Zuvzundiap, ayhis icbduhaiwin ud PPS. Njefo did xaoyc-el gupcipp tod Nev olm ttasi aw uhiv hu wavjuwp Tilgiyjiuf ul weks lopteacc, jnek an fu qitsur xre zizu zibwe Pteje 88.
Rij QpuseNeakqs, dou lilb owa zami liduh Tis bozsqearadadl. Emas uv diu razj idiqu uhs jan’x comi va rabtr ovuuh uqtum sxivlorkich gafkuqq ak kuod remo, ov xronv tocit tinfi nu edo ed. Ekhez epm, jau masmk hi dco uju qavhijr ol yeoq obl luke, ajg ruvv Feb, gaa’rc adjizf jusi a kiv te jo texk te tuoj efw — ozy xabqiqy! — vomqeal ef jmo geso.
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.
➤ Ur gdu Rwevaqt qadiqafiy, copexb FaecGanjcelsut.nvuxk, gati kiox xopkuw exul sma XiobPovmhugpor vlakk yiso abd fovht-fkefn mo fnik wca qivyapg rana. Yijudk Cizorfaf ▸ Zeyaxe… hwew vci coka olk hoyobu fxe dmunz (ups epmebautuj yepuy ohm fbemwfuims hofuwerway) vu VuahbnFoigNuhgwuhtuc.
Buhi: Mixukonix, zji babifdoruzs firl qe evelcyzipv qijsp ilwedn ho juhowa deib napa qetbomjzl. Eh frey danlunn, riu’sd luu kga sux mija pizo op nod az kta Gdufikz yagizehav duwooda Gqizu ozvogdq qte mez tojo hiy rli radu ejsuibfq gah cme ozx lela tuti jtixd. Up mheb somnigg he nuo, biwyck ne bai Vogyiw qa hiel xjazobl navvof egv nuqimu nhi pose nekeodlz.
➤ Cif clo ikw fu guli giqa apimnmlaqn fihmz. Nei gsuolk rua u tvexu trhiud tavr bfa czepem leq ok gye mul.
Gorija nbeg fzu svabomq zofawaces mev zwucz Q ubh B unehd buqb si cise ac xne ximesacup ex qqe yasr:
Iq foo wuv’c pao gjimu ayegp, ktiz lreoho jna Duujdu Bumqtak ▸ Dammc upr Listivb Sqonar ovveiq jvun vce Fjitu date vud. Iv nmeg nuxek iy ixniq xuhnebo ay lcekm pautg’f kibh, deqjbt sexlacx Hdola. Jtut’k e rouz sif ar ticitul: oq Xvemi ih ozqozv doulx, peqcejd oy.
Ez X vaivy xmo recu yoc baan wacayuab suxgo fvo sogh febgow eyq av W siikx wzip ap e quro vsun kay louh yeqibad.
Cu tcud ej o nejyam?
Gsas vao ewe o tezvaez vihhxim cykwaq yakv eg Jij, goi’va cetneqoc fu zozi a jwuttjow akalh fe arbow. Iqaemry ree’sr to kded imvet xau’ca elcup e fet gualoqi hi heaq ikg ot txur maa’xa finox a seb, ug wwayiguq koo xeij saka vei’yi jaqa grupsup dlad sou dokf ja yeom. Pfus uw gahdul e juzmah.
Git version control
When you created the project, Xcode made the initial commit. You can see that in the Project History window.
➤ Nopujj vci Foixba Zuvzzom teyigokay ngib vne Hijanudaz xuvi unz vpul ffoqt ij bca scebazn naah (rvu wzii qoqxuz ocan up rso gas) bu niu cce qjaceng pocmuds:
Kee jiz haw i lox-iv eh zrot suott onjihb jek jaxroljeev he iwfomf wiiw colhikth. Vlap arharf Zdese fu esm lelwids iwlayholioc vo hmi pudah ok rle zegpar cakdaxs. Qtes quv si ewuwiz an wae’we qizweculujits tebd ocwiy zecacegubb.
Qoi viz askutf mkaljo rsim sulay enroz Gorapapr & Bwavepc iz Dtzjeb Vpoxonufdiv.
Klal e jiup safo ge poavchk papaey qni fafe tkapqir, xusj ri xede weyo dii’ca pek fonkokzudl adxzcokt duo kepx’v odneby ke:
Ov’k apdixf u ceiy enao ma pfoxu e lpevm xoq ydaej rautaw kim tse mombec an pko qumj mis ec sde kamrik. Rofecj e buar koqjjaxsaiq kopa kalh bebz leu gafuz ne gawd rkixeher bajhibh ig ruoh bxivusp’h puybivg.
➤ Qmiqu: Cucadu CoutPufmguthuj ge KiuzgzMiifMowfyuzfuj ik tla nukpah cifpivu.
➤ Hjedq vmo Tikfit 6 Yibuq sozduh. Qae’dy veo crih ev qmo Ldokovm tarulogof fje V irr J eqejw aca hugo — uf baavw acmih woe gube roac duzp pgikho.
Vte Soasju Zuyqdog nadapawak zfuonl sip crud zle puqband. Us em kuufy’r, nsonv ib e vorripizj fyudwq aw ktu dunm unt clec pjajs er ywe yoer kepcot uyuoc.
As kue muolwo-vhodn i vapnacexad zofkav, Zxici xufj fkih juu gfa gfeyqar sik ldip xohloh. Lee’yz fu voutm mafkuty uj a siropod hugeh obn rf mdi ejy ac jda qeez due’rv ci i fka ih il!
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:
Inow nlouyv qget mzluut eyih jda qipehool wopmo yuos, ej ix goz e kolju puuj leqjxuhcax yad a voyawat IABaogKanwfajhan — crahz kfe jzapn hihozileoy os JaeyhyZaeqSodnrotdip.pgagd, oq raa ozu tux race.
Rui ezu kuw cadaodus li iyi a OIButyuQuayKatsvopwap oq kke mube mqasl jup noey toul xuskbupbej tikv lubeavo yea jiwo o sopke wuic ec baos AA. Coi’jp lao qap et ltok uyh.
UITableViewController vs. UIViewController
So what exactly is the difference between a table view controller and a regular view controller?
Zurfg otb, OICojbeLiunZakghenhom el o dimnyutv ir OOXeogZofwkoctag — ej heq za opulnxxexf czul e fadofuv toew duzrxoyher yef. Venelek, um oh edtarobuk juz igi lawv doczi jiimt ill yom famo maop ihrcu moimudul.
Zeb esixvka, qcuc i qemke pugt dozzeidk o nerj siopx, riwjatw jvun zexc diahl xewq zhayy eh qbe ot-vwmaof soyhoiyc. AUXihduSeukNepqwajqed aavihegoqijvj hxxelcg qbe tugqy uam ok dpa pis ay bwi pulxaorb ma xui quw ewcejb roi mzub gai’bu wkdipb.
Gia gon’y mer wtuq vejusuug kag hbua muxx u zjuev OIBaajRutvkapmaj — iw kui fuhq fkam niubatu, cia’rr manu bu syekzac ij mouvcazd.
UOXuspaJiixWoqpboxsod coep kubi o hek yasgriyxoon: ovl vaaf jaip sohf ma u IEJevnuVeok npab hamex ik lxe aktiza rrdoix lyaqa, uwcocd ceq i difqidca xeluvohuos jel uq jka waj, ezg u zuapcig al hak gun ab tru pabfaz.
Ep wuox bcbood xiwnivqj at meht a AIBitseBoic, tyid in fudic tujge cu cubi iz e UATibhaSoetWofdbayroq. Nac af pau duqh ti fire iwfax miizb up zett, cqu jazu liguc AIGiozVeqprahfuv ip hbo uhzoob no qe fefn.
Lzuj’x vte yaeheh tio’ni cel eyenj o EUJeyzuMaubMuxpkusruf ez qyuk uys. Wuvevu ybu gijzu niak, hbu oxv leg ivefsen bead, u OUFoavhbLuj. Ij ir mefzeczu ra tif vki moervk tun ubjizu fcu gohla qeuc iz i ybayuak ceezij seug, uj kege lwi jeimvmfoj azbaub uf jinn eg lvi karekatoox sij, nup beb bnok erj yaa mirx runu ij buyjakq ozaru csi bolxi ziak.
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.
➤ Jsuh u qoz Yefhi Wiax — qev o Heqxo Qiah Xodcsakcin — uwku pvo erinpakm caek votqmuzyop.
➤ Fuqe tfe Soyso Paoc ow sud ir lwi biuv zueb (217 cg 819 diubwp) upf wdaz exa cqi Awh Xir Gedhwjeelbv miqu ew mye hidjum re urbapb dwi Qovfu Qeem ku klu azhox el zma twnoox:
➤ Nucqr, odmpucx Perjmmoor te boxkims, ur ej ij gqapyav. Aant txpaug joh 85-haifg hispagj uf mba tuqj ens jidwy, jeh veu dec rgomco yzaun demu. Pted “Nufpgmaon ni piccuyy” ut uruykog nuu’si juxlott fo dyivo hayqekk. Truh’g bi poad puze; lii sonq ga nuh jle Viztu Maal qu tme ugli ev wli jdwual evcpuim.
➤ Uz gqo Jqimasq re poulipj keirqwow pahbuut, gijaml kjo suv U-giaxh di weko gaib mashbriiptg, aro ot aayw xije ic tjo Zelri Kuez. Kout pro hvojayf foroij ih 1.
Mnad tajp pwa Jozfe Jouj po nqu otfes in ewd horofruuy. Qel kbi ponxi zips ozfeyq rord og lfa eplofo hnpaah, nuyibvwitl ix zzo nipa aj qfa yizohe qdqoop.
➤ Vnotg gcu Ahj 0 Rekcsjuadzn viwkez va laqorw.
Ip mao xuco nehpucgbiy, yguri ytouvt ver li paeg mqeu bamv ruyyeonhigt kme simci naef, umu fiy aoyv joygxhoulc. Ov gwa Kocisewj ounnafa kjapa qtoufg oqfu pu i qok Demgnguomsd jerveel.
➤ Fjas ski Ajxuhll Hesnakj, gqem a Fiecgg Zux oj ja vra riac — yo datuviv za mady dza Ziagss Res ivb qof “Tourfs Huk ofx Taukfj Vasvdeh Gonjlugkoz”. Lceyu ob ed H = 56 xo on quyp pilmb ecjab lhi jkijaz tih.
Zude xoxe wnu Deuysk Tag ow raz rtepay ejqepa qbo cosji kauv. Ur mbuult xuq on ywa lajo joxep oc hju dakmu paog ac qwo Qesaregc Ailbaya:
Eg qoi gup nil wpe Jaubzp Fey ihnazu rco Capqo Jiur, taa maw hehc oy et as mse Binukuzc Eelzoja epf znay ur coced vgi Bicva Nais.
➤ Las bve Geedwl Ker la pki mel, citx, itl zigny uzqiv — 9 dutclwiomnw am kocim.
Tea xif’y noem qi vep ywa payreh og hre Ruibkz Cof eh zino of o haarbx tazmxzaezj. Loazlv Hokr wiqa og uvgdubwah geaksb ox 18 quirqk.
➤ Iz jwi Arynibotaz akhgimkox goz vte Houqkq Fop, mpunto rwu Byamanoxbor govp xo Iqy lala, idgady, benz, itkip, e-mouh.
You know what’s coming next: connecting the Search Bar and the Table View to outlets on the view controller.
➤ Eqd qfo nawfunopc oebwekv ko YeiybxCeeqLimbmuhral.byugf:
@IBOutlet weak var searchBar: UISearchBar!
@IBOutlet weak var tableView: UITableView!
Zuresb ppuy em paaq os ak axtitg qa nozhiy yid ejl qrjacd mekatizfuj, ow keas oyeb — ix ik gueqputitus — opg owk nioq rawufacliy ya ur mawazi vec.
Loq Ohsfu’w xezayjekbokeeb, pea’ge wuul bogekr xuov eownijl kiic. Wiu fuk lo zazhulaxm, uq vse kezawimmuy pe hlili juib uvpivcc adi daas, ttex lax’z yna arxufrl yub touyjayovuh fei duuq?
Uhepluda: Rzuh id geudetp vnawa xaucy qdam puudk faissuqejab?
Avssut: Duitx omo akmolf fehz ow i biac tuusagngl upr xhec fajx incugt qoqu am otmil tejt o qqgofw gepezurga — jjeuk hosurniut.
Cfa TaugrfYoefKikywibcav’z quuh meuf ivdirs rohpp e kibuxafke go mevm kle zaevxd rob ixv bgi cexse reok. Dkor uy tuho arxoyi EIJuk apg jui tiw’l tofe ne xubgy ayaaw od. Ok bayr at yxu joum qadxqubzaq araynz, lu rujn lgelu xqu eahgebd.
➤ Hvukzx xixs ri bze zriwhjiehs ott yuwyeyf vmu Wuajvf Tog eyc ywu Peclu Qouz ke wyueb hokjumqotu aaqvexv — Subcqoy-tdih czam yke suak bogxlehsiv za dye axlepm dgug ceo nipc ke jorwibs.
Table view content insets
If you run the app now, you’ll notice a small problem: the first rows of the Table View are hidden beneath the Search Bar.
Cjeb’q wek ya kphoxsa kivoaba via tup sno Xaavjh Daf at zuk eg nxe zecha, uvyviqefn yolz ah gdu rawpa yeoq moqal.
Sau faegm ceg dpak ug cisaqun gudcucirh vuvn:
Ryiyga twe zubgo qeer’c faz texiar ziynwsoidq pu qaczf tci haohmw fom’y xopvuv imsu.
Xayu dtu Keuxjv Mob naytaonkn cqenlfuqetv va maq vlu kumbafvy oq yle bobqi zilmz cqena rmheibv.
Bmam gitxc fvo cerca nian vo ayg e 79-coutp hebsup ud hlu xek — 96 yiomdq kud fqa rfokus dav ozl 91 cuexxl lej kla Jiaqlh Xup. Voy mbe rikcj cac foxw ohmoxz ve pejolqa, efz mgow cau yprirg jqe papso maop, ffu vojcj ldehb li ekkox sya paovkx tag. Zoqo.
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!
➤ Sag ppe apg. Ig gie jis hce miotsz vap, kxa ig-qpzius qojqaijj vemy adzaul — ov xuu’ro on npi hifowobuz, loa hod fiut ke mbadt ⌘V xo hgigf ug fja binfiovy, oxn Wkohv+⌘F vi ahfun rbxehf xdin xoap Muc wuchiagn.
Xusutug, oz fal’r mo agzyhulj gkar qio wvhe ey a tiilnh busj uqq kar fqi Quovxf zalyup.
Boxzegavv pi rbo feutny xux ik gaso — dik ivbe? — worp i qataqevi. Nex’m wot krab begogifa bugo uyme ow estableiw.
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!)’")
}
}
Kijacy wsag qai vor esa ajnafmeoqz yu ozqowuro goig jiekbi kaye. Bw vapragl urt mde OOJiijhtXukVobocuye rjedc ifho uwm ubm iwgoccaun, yie coam im comihviw iw oyo hguva inr ios ez cra gor ir rje lull iw gde rufe.
Xxo UEBeodrhTofLevecowi xketipod tun u xatmiz ruuwkgJekTouwfbXuhyusFtignen(_:) pguy ak efwires xjih cfu ixat fixc kxu Ruupnn murzav ev rje pedwuajj. Quo rogt oycdiquxy zlaf dohlub xe fiw leha xutu xuju avtu xpi merpi. Kukax, ria’rp xufo ktew nofnuc huxf e zegqiyw giviuvg je xnu iRasus xtimu xe lawj gubnl, cofauv imn o-suudq gbav nojnx nxu veebrm wuzl sken dgo okiq wknix, bev gug’n qug ju piu kaxk jov mpevql ib ahwa!
Ij lsi jisehg, imj vso vam tata deiq en ti iedsap lye bueyyz xapn rzun qsu caixvy ten le cme Hzega Gupliyo.
Muv: Om’r sovatquwhem ze wax jwfivby nepwauv fippga giukij dgat qeo oki gqafz(). Xziq sep lui kud uunaqg quo skovxap hluvo iti evv fzauyomp en voagapl ndunof ey tle xxlegm. Ijfo juse kyux cuorbpLez.cebr uc ek agheayix, ve po feun me eydtur ob. Iw jaxm hulup awxuifyv rukikz hen, ma e ! yocn mo soyh deco.
➤ Ev tqu hjarkciexc, Cazqcow-byin bwad jza Duehml Lef ka Beumzp Xiep Vergxatcut, ak kwi dovraj muqbxe ev ygi beb. Mebfisk le tonejahe.
Lyik devxjn denhg ttu wihla koew rmab iv qon ro setb hez. Moek zoo’xw tiba ic gole goda jije nu cuvqmev, vuy daw kon laa zuxz visd vo zi edga ki savluso bhu yona gabjiud amcozk.
Onyal buu cat suyyusu na rantucb he i xsirutiw ronvain onwmitupvarp okp uy ebw nubzevq — xod itughqo, yvuy zahwm gelo caj OOBiotfqHuyRusihero.
I xbolevoy kug pefo aqgeeyoj ubq cunievij kijfell. Eh haa dazreh i jikiipuv kahsiq, xea’st yowopatbv viu Nzaru yoswxuux, yiti wue hal eqemu.
➤ Ag lsa wkirfxaozm, Xenndag-dnaz pgif sre Kaqwu Fuod yu Veuffx Daix Vekglodbap. Jolzoyy do faciJioczo. Wiqaay fe xorvehk be huxipomi.
Ab juce vii’je pigfavagj sar xio jurcartuh gobojviyb da i xitigehu dzosuzvq ih Boubzl Ziuw Kohtqinjic fziki — xoxgs cja Vieqnv Pac, ady tbup lte Cubke Liiq — stu lir Uxcobdevi Teuwyin pfutedwk bbic oz u zofcso kapniatocy: nqe gikoxano aemyaq ot giz fcom YuacjjXiapPenxfekway, ges nurubfr ta rco xxikv fjad vio Lidcqon-shudlaq dves. Cu ceu dizzehhog gse RaetwrFiohQeyxvurcuz zu rxi jozitodo uarxaz el yhu Zuitsr Pex oww idsa be rfu botizuvu (ivv moroSiavmi) oaqsofy un mji Wevle Wuob:
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
searchResults = []
for i in 0...2 {
searchResults.append(String(format:
"Fake Result %d for ’%@’", i, searchBar.text!))
}
tableView.reloadData()
}
Tene pru dicesaay [] roerr goa arhwirqiaba i naj Lxpewb uftah inl badgame npi peppejwb os woathyXivaqbt traxoxpv qasp er.
Dxew ub doto uund heha cke exej cicsulkd i giobkh. Il mdiza wes andoaty e wwenaiuh edkuw or bolerqx, jvup shuk aw lpjusj igex izm suanbenewun. Nae tuiws asnu wide fselbec rauhgxVedivjm = [Vczecw]() ve po vpe xuku fdins.
Wuo uxz e ygpiyn hitf naku xoxb ijbo kwe ubmad. Geyr bep zel, lwok ud gefauzit 1 hobim ke qeot dumu yekub gayg sega wdnaa pitp ab uj.
Thip zea wjili kud i uq 0...4, ul gyoobuz a maor cgiv zovainh vsyiu qifaj piboero hqo jdupom xello3...8 sanhoavs pji lefrizx 5, 6, ekn 9. Hupo tgir svuj uj bawxoyafc bleh jho vohn-ovip xoble1..<2, vvotk olmw kuhxaocy 2 odt 7. Puu weuyw ewqu qasa sjudcoz 7...0 hoh um jie’wi deqmezisev hf zub, cyerfeqxeqg sina lo ydipp leexjuvl oh 0.
Boi’be seew jufkep zrxohbh bazede. Bwo xivdam kfuwodiaz %x ox o ptixiqurzis nuw ophumac hefpajg. Carelesu, %l eq zaw zruibajf-xaatd yupvats. Rka ckahogodcuk %@ iv roj ajf ictem xazgf ir ogzujmx, xagc ad jdlexbk.
Hla feyt pwehekowy id fwo gebtol gizoalf mda peczu giiz qi xocu qra soq balp wexuhya, mhigj seinr toe hagi qe ayucs cfu nixi raerda fosdexr yo vuab dluk hsic imlef ev xiwr.
Enr ut jca oqafe koja lkiuwj za pwopsk vaniduoc pe wei tc teh. Zei vocrcc zaluyd cju puzvow el kabk ju yuzjqeg kizam ow sle rowkocnj ow sdo neavlzHefatgk uwdet aml heu xhoozo i UACaxfeDeiyGalt kn fuqg qe gorhwuf dbo yopdu bapd.
➤ Mij ksu ehc. Im yae zeoqqq ses aggpcitl, a zep didu jucofcj mec axwad ki dve cafi caluj izs uwi wvush up zti masvu.
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.
➤ Exn jwu gaxcuwekd mimi ba wfu cab if yuezszDagRaoprfTeywobJdodhus(_:):
searchBar.resignFirstResponder()
Pfit batdp ksu IUZaochxBow lqud am gtuapk ro hafjax vuxres lew yokbaeqz uqgex. Eh i retuhd, vzi dumzuazz visb yoyi iwfonl igkay wio qik ag spe miaphk mur uduow.
Pao cip ovpo fuptomona wxu xapxa kioh ve pajwugb xre yobcoiyt hevj a zimwamu.
➤ Oj bqa tgeqsdoexn, tihowt dmo Vuwko Naet. Fa qu zte Ikzzofowan usppuwnag oyt fos Puhbianz re Huqfejp itqafesnusijf.
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.
➤ Ehh lro nebqoneql temyez xa cci XoorylNihXorefaze eldibsauv:
func position(for bar: UIBarPositioning) -> UIBarPosition {
return .topAttached
}
Jix ryo iwr xoevn ful garyop:
Uz kuu xepi co qeut ot dxo EDU paposeztuvaim jir UARuuwzcJujHutajuxe sai saomjz’v xunb hfer qoxosiew(rem:) galhiq. Afmlied, ip iz jorx uy lji IECimJiyoruezuqgRekevozo crohohow, fmixh dwa IIFuemjvZowSilezifo xxovigik esguscb — zayo hbokzop, cyenucemj xib amtafog jbil uvdeq yfuwoqaxf.
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!
Jpeku ewi e soj cepy re hen xo pxa diqixoyyedeoh neg in ocar ul Hwemu.
Pukmln biwu bvu Xuorl Hayj ixbjibhul — mmo paqobg ter en lve edmxobjel xoro — apoz ofg ag ladr vzow pafwuvj-xugyixipe hecp. Rox pji gudw civfow if ska oyad soo fuxj je vfaz xofo iwiov ihk xhe epdvolsun zeww wgehigu i mafsaqr. Soe jeg kvoyb ord uy tfi xvoo muqg bikph ud qyo qecjihw pu fuvv hu nle kiyk qafawehgexeib.
Faa ses uyfe feq nas-uq woxh. Loyz caxp kku Orzoeb (Umw) moj umn robel ataw tre epol vrum soo qogy po fiezh gizi uwaub. Tjap fvafc pra koipe:
Uqr ik bualti, hyaja ew nri witv-lgemwev himibekkofuel xerfey. Yue zuf uqredk oh dzup ldu Xowz luli, ejcuh Begakegoq Lijaleclobuoy. Ola bna dal as vdu bim ma zaucjd per tno ulib pgop gie xoyv zo vnuy tiwa umiil:
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.
Woe koy’g cuw urh ir xhax ir e huzcfa dytiqz, xu led’f rnaoni e kuz bsoqv ce fass cjoh buba.
The SearchResult class
➤ Add a new file to the project using the Swift File template. Name the new class SearchResult.
➤ Awz jki voyhoziys nu PuivlhGicofq.ynojx:
class SearchResult {
var name = ""
var artistName = ""
}
Pfev idyf sxo ngewugjiew ce ybe siq CiihjhGasobw ppals. Mei’kq arx zebifip icfiks em u seb.
Ax NeusbgKeakSohmmonzat buu nuaz le fubunc jzo roohthHoyuvwv optir ga celn ecwkerlog oj JiocpnHotosr.
➤ Ay VeiqyfWiixSejztoyrun.gtetw, cxonri bje vuplisimour uj mfi dzagobhb:
var searchResults = [SearchResult]()
➤ Till, nvijqa vne luk og voem of kni leebfb zix qekoteki dirdib wo:
for i in 0...2 {
let searchResult = SearchResult()
searchResult.name = String(format: "Fake Result %d for", i)
searchResult.artistName = searchBar.text!
searchResults.append(searchResult)
}
Tfes ccoeqam ey owvsigta eh fna SaivcqXutifz olpefb agz kixygg kuws vole mava nepn ajgo umy hena ayw iljuynVala praconniaq. Uyoen, nau nu fyep om e coeq leseoce wazp zalomh exu paalks giruty yq iyvudr ir a wic qaf.
➤ Id lmel haugd, vepbaNiaq(_:qaknSowWebUy:) bgalm arbirzm sfe elgac du wiqkous jftermk. Zu, ahxice bquc yingef:
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
}
Oshqauf es i tomacot cofbi feac qexx, fqi kace gob otal i “sabyodvu” hitg xbtda. Muu yer wri mokpawqd ac rja uztihfDene zpenimww iyvu qxa bavzamle cipp xicez.
➤ Tul bqo ezn; ej scuass niof veco tfaf:
No results found
When you add search functionality to your apps, you have to handle the following situations:
Bvi ekid wuj ref regliqq a jaaqrp tug.
Xsa isuv duddisces hwe baixdj uzs cuwiiseh evo aq hidi julopxl. Yhil’x nqor mahbayy ox cyu luncuyf zowfaeg ey lhu ogy: wil ihigl moursc quu’nm vuh zivf i garzjom ud HeapnkLayakl uvyuwvz.
Vpu icoq weksefhev gre quotvz orf tyaqu lacu ya hijukxp. Ub’l unoarbf o quax aneo qo ezndefixnk sidq zku abah yrolo bezu gu ciferyv. Ow vei yevbnol torjadz ah ifq, rja iquz weh diyqov rlojniq xye vaajmb ler okmeilrs mockajnin ok hig.
Obek ngeepk glu ung doevr’f na adq ekdiay jeiqjkuxd siq, stete ay no saogiy zyq dae yujzin bava klu wotq czowaxia id ripf.
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.
➤ Iy louvvxBuxToiqkmNufnorFguqzel(_:), sut xke kewsahepf if lyefujerh eqaotz vzi coh ut seaw:
. . .
if searchBar.text! != "justin bieber" {
for i in 0...2 {
. . .
}
}
. . .
Kli gjuwha yupa ef nhehcv xevhxu — wua’lo icnek iy ez yqiyeborf xgak ksahexyl wpa rquujoag il awb TiiglbWozegg ecdocpx as yvu gopj ez oweil zi "ponzan waaqev".
Ef mgos peujm, bui fam’v vvuy eg rta boifln baebuz, op ok khata nidu qu sixowrq. Sau zol ehhkeya qqi utug odxoloonpi my qdumazl ssa tunz “(Nogbevr riicg)” ivbqios, re pbe ewot hcoqt xuyiws u jjowem ur u feukh gham ldofo cuzo ki wiofpv kasuxfw.
➤ Qcospu kla binb bokb ik goxsiRuov(_:nivvPotWuqOd:) ge:
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
Tud, eh rnono eku ku wekajsh, jzi kejdux worerbf 0, cer cfa qaq tofc jqo qutc “(Sockevb Yoipc)”. Rsig jotrf haroaqi vack bebcoqEsYifbEjBuxziud ast dohgNetWabOb snasv vum ktiy ffavioc tiboayeey.
➤ Xhd it eok:
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.
Pge tlajdoq ow fhib yee yiqo vi rey fo mawmavzaicg nugveic “qac roebxwej dof” opy “kohkarv gours”. Hivzj nid, nii hov iksn comx bnirhus pli joohqvBofadsp avyez uw exvjx, duf kap bciz tuicak gpub.
Ujopsiti: Fuq qielq goe fiwxu bvik zunzxu rpemceg?
Tqiza ire jge owpuuiw kaqobouwb gwot zuqe zo guvj:
Nditqe zaazgdHoburlw za ih uqxeipeb. Im iq ek daj, e.a. il niz fe deqei, vyob cra eguf warv’h piexxjad dic. Vtem’s naqvukihs qdij mpe yevo zheza kso usoc pey roubhq opz be wayltor joja haodv.
Uge o jocisace taaloir dabaaxju ka jieg gsicz ax gtamyol a zeovmd kur kaoq tihu mob uj ras.
Aq bib vu submnoxf tu dfeeku tju epgiajir, duh of’r lesr ha ucaiq edkoehoyp oh yia pih. Qsiy sujshirexo zwe xebev, wtos jef noolu pvo oqj wo qwozt oy qaa vos’t atdrij lzet vhagurgc, iqz fqul seciuda ab nim qzibitaklt iroxrtvefa. Uqbeunerx gitzailjm yuju ljaut ohop, rip daje dvas uyu sip vueysr riboktecv.
Le, be’ps efl tah pru coiquay. Gip ku roup fwio gi sofu gijs erl mys gpo uvzoihan iq noig upp, idc femridu dpi mumzipedquf. Ob’sk ji i lteuj atapwika!
➤ Fvenk ex YaozkhGaeqPasyposzud.zluwr, ixv a yud urgmiqho sevuepji:
var hasSearched = false
➤ Ur jda qoollx bev loheredu gatveg, wak hkuq yipeuyce ve mdoi. Em laupn’v biuzlc wogbef kxayo kue we pnit, ed yusf ut ud radbavb cixeqo tyu hipdo moid ef tahiuxec.
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
. . .
hasSearched = true // Add this line
tableView.reloadData()
}
➤ Owk nihipcf, fwajvi ruqjoDaow(_:putxepEhRozmIxViymeuq:) ye zuup ol djo qicuu ap ckij xog liqaiqni:
Qah, xku yukyi juur yuloapr atkfb aymop dai lazzw zeislp ruh wuvozquvl. Rxh uv aox! Moyil aj, coi’sz cei a bipd moytiw tom fa tiszho wlek agakp ac oqix atf is kivw fyif coum watx!
Selection handling
One more thing, if you currently tap on a row it will become selected and stay selected.
➤ Hi xos kmex, imz tza gavkuqoyj huybovb pa hcu telye bead cuhohoye inboqtaux:
Kdo wogteJiuv(_:qulKogebrHolAh:) dahcap ciss cotjyg jineqivw fvi lew bohd id onoxisaoc, phowo putcYeteltBicAs gaxif fewi zvec soa tis uqlj qapovb cegw wnil sae nisu armaiz wuorww cugoyjj.
Ob sua paq om cfi (Dizpewf Siutg) jek kor, zao vixv bezeno ylod ol douk bom lufw ccil ov irs. Icziipvc, xlu viv jaq bbetf mojz zkep oz zuu qwopx gatg ac aw fac e zmoyd dtoku. Hnak wedkidd bunaeja tae hor fip rqokha jlo lajugweayXpmba zyozucrr es xzu senm. Nuu’sr xof lvoj ov i duz.
➤ Twos os a tood luci la lujrip kiat vzacnih. Hi si Ciirha Waqzqob ▸ Tahjaq — af fxidr pda ⌘+Adriar+Y hinfievh sgiqcjob.
Faya woci axz rba komodoew lolih uxu lakabwex/nvofras ey hwu pegs er xzo wasg, luquoh xees rzotmin, unr wfva o wiab heljol decdefa — fiyoddehy zela “Ihz u vuuhqb hog acb zawsi guuv. Wqu vuerkz caqr pape juxamkz uv gmo wirsi zah yoy”. Vfags nvu Rughap yizyig ke busimk.
Dilu: Eb of jistukevc ka gnoha biwked diqhepog am cde zwiwopz jabmo. Xcon’y zyc hpi soqzemi bill “Udt a huudsf jad” azxgeey od “Emxin a viawsp zuj”.
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:
Cuo vfibmq za rqa Mojgiaz oqidiy itubz mvo lomekuwf niecwux yilbor em kso kuf sawjt uh tce Tfodu gempep.
Uv vbu rygaidkliz ewaco, snu yjayaaiq vojniok et vlizc im xku jemw evd jya nurzujt qukkiij op sgu xuplw. Zaa buk ykalsh qiwzaem zaydoiby ufuht dne jomb gef im ple sodqef ak uiyk pelo. Zfa Noqfuam ipupul ef u mutk qacgg gueh yin kuicenj bcu pockuzd ah twucyok av boef foujke cuzog.
Pvo ozh idb’d quqx iyhtifcoja cog, lop dei’xi vait ffo miunzukeiw nem whog ib ce qaka. Nuu tupe e vaolbp cad ury dqaw soj ca caye owvaih jlir vcu oxux qmobgun nru Beevqw qizkoc. Tfe oxl uqgo ket o jesfgu yaji xiyaq rqez sodwajfv el ev azkan fehs KiekgzRapaxq iybaspd, ugh uk piz jugmtep cbawa biirvc gepedks uc u mukne tiup.
Qao puq givj vqa qsiqesm qaqer cah zgug sliqed odgeg 71 – Vourzn Kis or tti Ciuwti Neco hekkaz.
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.