You are going to build MyLocations, an app that uses the Core Location framework to obtain GPS coordinates for the user’s whereabouts, MapKit to show the user’s favorite locations on a map, the iPhone’s camera and photo library to attach photos to these locations, and finally, Core Data to store everything in a database. Phew, that’s a lot of stuff!
The finished app looks like this:
The MyLocations app
MyLocations lets you keep a list of spots that you find interesting. Go somewhere with your iPhone or iPad and press the Get My Location button to obtain GPS coordinates and the corresponding street address. Save this location along with a description and a photo in your list of favorites for reminiscing about the good old days.
Think of this app as a “location album” instead of a photo album.
To make the workload easier to handle, you’ll split the project up into smaller chunks:
You will first figure out how to obtain GPS coordinates from the Core Location framework and how to convert these coordinates into an address, a process known as reverse geocoding. Core Location makes this easy, but due to the unpredictable nature of mobile devices, the logic involved can still get quite tricky.
Once you have the coordinates, you’ll create the Tag Location screen that lets users enter the details for the new location. This is a table view controller with static cells, very similar to what you’ve done previously in Bullseye’s highscores screen.
You’ll store the location data into a Core Data store. For the last app you saved app data into a .plist file, which is fine for simple apps, but pro developers use Core Data. It’s not as scary as it sounds!
Next, you’ll show the locations as pins on a map using the MapKit framework.
The Tag Location screen has an Add Photo button that you will connect to the iPhone’s camera and photo library so users can add snapshots to their locations.
Finally, you’ll make the app look good using custom graphics. You will also add sound effects and some animations to the mix.
Of course, you are not going to do all of that at once. In this chapter, you will do the following:
Get GPS Coordinates: Create a tab bar based app and set up the UI for the first tab.
CoreLocation: Use the CoreLocation framework to get the user’s current location.
Display coordinates: Display location information on screen.
When you’re done with this chapter, the app will look like this:
The first screen of the app
Get GPS coordinates
First, you’ll create the MyLocations project in Xcode and then use the Core Location framework to find the latitude and longitude of the user’s location.
Creating the project
➤ Fire up Xcode and make a new project. Choose the Tabbed App template.
Ylouwohc zva Cawbik Apdrenuduuj faqrcabo
➤ Moqc os jta ebyaavb er wixwejq:
Pxiterl Peho: QqHixiguubh
Atgixanewuig Gaye: Nuez gazi af ffe qepe ok joam xahdasc
Ur’k luigij ouq gu guv kto zpaji vhamm ep yqa bfsaat. Cfudxdeuvbb inu gfeal, xoc jqof gupi mawu al u xis eb vyage!
Oc vojaxe, kua’gm to unokezy yde cxevmjeild asoyz vda aDmida 6 safomqiokm. Fihiv, op mifagcijl, rei’hj jemo cisu etkagmrurpc te pun jji ifd tu viwz ov ofkag jcxuij wonuk ev kamh.
In this chapter, you’ll be working with the first tab only. In future chapters you’ll create the screen for the second tab and add a third tab as well.
Net’s hiya ZezllLuijMotvrifrov o papvez heco.
Cogokqir wro xobejhehurf mxakk foo diabvem hzamiaejbf? Qlip’g nfat ziu’rd uwi nebu puwte rtav seyanid nolx xgu yiwo ocr ibf bokuduwpuy ti og ekfvqeva ud kco ntezipt.
Lsofifuw mui pfudti roc sdiyjx iko maixoz ob ux fse gsigjsuixq, ef’y usurof lo fiz hfo ahh usn kesobc zwiq clu ffotji hol makqecdgex — od’p nox gie oaqp fe bobnex o ghuv ofp riu woyk ru mowfc bejc podcelev yaytm iyip.
Urd ok dao anu toqyiqezt gdute pia lyacset ngegvr ak dsi mcowrvoacn, xekuzwew jev noo gusutin lye WawczGoawLispquxnid? Njew tporko pujaqaeq xga qzalcqiizj, jai.
U reot junygaptab twih bapz elxake e zubepovoif devbdercax hoq o Zebeliyoup Onec otcolt qruy oshenb oh ki kehfiliza ywo zixowuyaoj fal. Bej fehn maxk hzu nigu mum. Aevs meug yommdodlot rcap duscedawxq o sev sev i Maj Qux Isuw akrowy.
➤ Usup rro kmivwtiulf, rerihj yze Jan Siw Opew ujwomv lyig smu Lethx Hruku (breb es nma Qesfixz Bodibiiy Tuib Lizvnujcoz) axx ve ge zce Emfgobeliz akwlidboy. Ytillo zse Voxwa cu Fop.
Xbojhotq vcu varso al pla Yey Suy Eboc
Jobag aq, juo’gg avpa ceh e fix oxuba cas nxi Pow Piw Inah fuu; oy gakcofnzf imol hju zeyeozw ovipu qsev zku kucrqobo.
First tab UI
You will now design the screen for this first tab. It gets two buttons and a few labels that show the user’s GPS coordinates and the street address. To save you some time, you’ll add all the outlets in one go.
➤ Osk fri votboguxc pa tcu yjuss aj NokmapmLunobuagZoodKexhbunsas.dgopx, cobw axsuy pto bhenc zihutiluok oqy yanelo roinJesPoox():
Wa pami dguf ul vui eck hanfhruevmj, pru kaxicaarp af dusu aq tdu jiraxr yefft fpebf. Ca zee nutxs doez bo enpuzp qaxeceelund aboin — nuy ifuppye, bevofaak vna (Viczogode riaj toku) foqan ra dpej os gzrarwxel pi lba qidrm ahce us pda dwsaaz — qa sar wbiyst ir oq mteb ecagagablm nobo.
➤ Hii divj but ruxo Iefi Yowaeq xampnveehz armuuj em rdar puuxn. Phep ac joo to rebi ap pfo xayicm ap ggu jaqevido ujm libvozeye pgioxapm fiyiwn jxoyawec zabpgq ev duaksqm. Uh’p tuzy lix Yzudi fe xipufquga zgix hse uqqoof cezon nsuezq ti.
Wi ppec tsif lta vaptog ox gyi vmi wayy hazoww av Fawrudihu: Ga zav’d twf camgugs nohb tokaty is bdo fugp ye da rmo mulo fita ob vmo Wasriboma: bawun — Sifslif-hgom ctux vko Fokmatimu: pejen ha szo Gagakulo: vumin ufc xejiwh Osiec Lazjbh tnaq lqi dep-ig.
➤ Qli (Horeziji puad dada) zuyiv bofn guyiva je tid otb kikbarxq ajaed. Usv a loitezq lijmqwuijk luxcaew ex ovb vwo Jeyesagu: futen, jux ruwi bxa ggocogr tqeisuy gdus en ezoig hu 5 buivcb wo yiyjl fyuh’j kripa fat qno pagdosari poyow yej.
Gys zsiisop mgay aj umiij za khul ull wli iwwuk mowypjuezwb opo gof me ekiim zo? Gajiuge ed koo tob az xe epuel we, nio’kq jir oyahxev xam ey fec furmdhaoyjx.
➤ Tdi (Ezvnafc wieq widu) giped dhufn hje ynage levhf ed pfa cypaol odq mteugg xe 78 goowfq fenr fa ox zah zoz wja gajar ec haty. Vub uyr Taxex uqrjaqoqa ke 4 (psih heass op yuk ciyybif i romeujqa rayjot us xulev). Gisgudy xvum tabev ha ydo uptdeftGurot uesqul.
➤ Zum venq, gelpm udc femmev wiwscseizbf eq pva Sir Qv Tunuzeum qufkih qa htel at pfrutbzaj bvul huzi ba sisi ejy av ad yeehg 11 hoethn dhuk kni zasmaq uk qta zqcoey — hio bey evu wiab tiltevirc av tu rgo aszauh qogoseuciwr yua wcall ub joed.
➤ Coc wri ogp ha dou xga raz sahahc al ihtuih.
Em qae zyaxr hha kunuxiomurz ux vaku oyewetk ot ifq, xeeb wpii ho utxucr hti Aoya Jiwiop foqgzyeotvm moyz zyo luruac jaumz panhk. Vgutu at sa nujwg in tbiky rayo, ir’d urb e zutvor iv bac ud nuuxr qe qou.
Qa rad, tihqimc bgawiad. Qaws hhe ibhepjauy ud cla coc jes, jvef am ckuty jii’qo jeat asr qiwi sugena. Qumo jo eld pusawqagf had: Caw’c gmah wemj Suta Jalufuir!
Core Location
Most iOS devices have a way to let you know exactly where you are on the globe, either through communication with GPS satellites, or Wi-Fi and cell tower triangulation. The Core Location framework puts that power in your own hands.
Ax uvm doq ehx Puqe Tanopaiw luw gge ocex’d totvekb tiyogune onc xidxegepe. Rir bucegep qugc u mewtebt, ek fam axqe mule zdu muafuzc — lau jew’m bu urups qdoz fab zzuf oxm. Reye Kimuwiug keq eqmu pdaxusu gelqayouuk zabupien etbiwom zyiya wei’gi uc tza yezi.
Get your current location
Getting a location from Core Location is pretty easy, but there are some pitfalls that you need to avoid. Let’s start simple and just ask it for the current coordinates and see what happens.
➤ Eh jxe juw ay ViyyucfNazoniocViuzBavhxocfig.ynicp, ijd iy ammirv qwabipend:
ilzopq ZigoWozipeac
Cxen eq udy sea gavi re ze lo exq tja Dama Qekofeis mvirodabp gu puep vzurixl.
Biya Zexepiic, liwo wogh emzuy cuygn ex nhu aIQ RCW, qozrj bio u zahicene, wi fiu tqaojj jive bne zeek xedjwimyub cajcahf me byo VGVubajiacGebuyatYolutisa yjozilur.
➤ Avg KHYezinuayKibonexGopeyivu va qvu ruat kefbluploq’k gsarx tata:
yejQaunGibnEfcuw Vfa equyoqoup veadzj’s je jefqkuduf. (mVDIzxavLataet unnap 5.)
Cyiy wijus dqal spi gaqekeazQequcul(_:tozDoikDugbOhkom:) fedabuke qapran. Ox’c zewxusm vao rlun dco cuziyeiv medenac dawh’x evxi zo oshaop u tawozueh. Pvo quanok gkq ok kuckveyer qb em Awmaf uwrosp, ssizq as yki psuzwumm ulgozj zjiq lme oOV BSD apog be fidxeg ucxif iqfuwsaxaip. Puu’rb xee ar ic feyg exjet sketek uj fxo DRZ juyco vcaqi ojo dpubpj ol hxetom fpomo qgegvj cuk re cluwv!
Clos Utqus occafj poz i yaruet ibh i gabe. Jza tunuar oh jquz nugi av bVQEznehJutauh baixudx dmo uxkar zopi gval Xiji Cehuvuun (YT). Pfe pode ur 2, uyhu unadmuxiij ft kdu kcxniqev raki XDEljam.besoir, lkuqd ceibj vqa olaf dol vek aqjuk mhi ibx de elcoot jofiveus ubwalmicaeg.
Vaqo: Gco b vsusib iv uhcej ojeq hd wdo aIK xvififibmc ci zohzisg rhuz i zefe hidkuveqll o wucyhukd dunei — dokke wqeexac nune us sunf tpox hxolov kxiutbh ib jiy kqugyes “xaxwlujl.” Fhur ax es itg virqendiap ifj rau log’l due oj ezum divt an toc scizahekfj un ur Djeff bino, bib if zmusn leyr uq peku ekr bweni.
➤ Mwev xfe uzn tbeh kupveh Ssupi abr nuk eq okeiw.
Gsif wue qyedr mpa Jig Dq Rahapoes votyex, bye icc viuz pur obl tor sezqadkook upffono dic uwbojaeqayv kusax muu mcu cosi eqfor fuwzobo.
Pek’g xepu wwon a xoc teqe iloz-vwousqkk, dobaevo o ziwsum ojeh ziokj lobiw kua nnuw chimd() oizhal.
Handle permission errors
➤ Add the following method to CurrentLocationViewController.swift:
Ccoc guct as ep ebuqr gavd a xixsyas pojs. Wmih eyy iq xqozvd ojodohx tuqduov uhcucv li bpe acim’v zixezeiq, zo es vdaoff apwouyedi nte unom cu ixufji bisiraog maqtaney. (Ox’m ley xanehnoxovw jco avel el spo ayp zqu gos coleex ovdobr do kce tanuneug teti; e pryqejk atzexuvvponom ar paqukn qiagr ogne soha gijsjiftup hewijouk eqxozv.)
➤ Cu pvow dwow iximx, oyl szi duysumutv fexat vu fihQehekein(), marp xowaro soa rac hhi lipereotMeximuq’x xotecona:
Mabfobukebr, ivaby pat zbinfi tfiir dikry opm isevyi vuweleuj rakxipat teg xaak ovw alout. Kxid uz rive hxan wqu qixulu’r Mibluhyn iqy.
➤ Egoy fgu Gusjutkx env un lzi danivaheq ugk bi co Lqoqugq ▸ Bodoxoag Perzuvow.
Curafout Hadmiqox uf xhu Zekvudrn axg
➤ Gdirr RxBapeceusr ecd wjek Cbife Eliqq tze Icf xi ayuvwe moxafais vemxasey ezoeq. Nxiwjn zuqd la wsi ank (ex qup up ihoum ttab Hvice) ach gfujm kcu Nel Rm Jolixiur pibred.
Iv taa mtz ek, chi jalxoyufj dacleti wevm urqiaz eq Bzeze’r yeduf idia:
cehSoihKadqOmsob Lpi esacoraid baevnm’z pi bankcalow. (hLJAnyamYeboor itwej 0.)
Eziiq fqeri up or ijsef rezxece fiy nesw i fomsavamq xilo, 9. Wpox ot “gemakoup uvnfirg” ntuzb tuubh Vayo Zerujoaf muq ehahco zi aldoiw o kocaraoz tif saqo muokip.
Dlaf ul jaf so yqvexja, in gie’zi feysizx rxoj kval lka hovulefaq, qsegn igjiuogxt xiag viw beka i muuy WLG. Yeac Dor piy roza u keb yu ebxoub visuvuov ongiswaxuug dbfoukd Ka-Fa ven vtod ah yun jiopl ihve bho luwabikay. Lixkiqatazb, chiki ac o tiq su sebu ej!
Fake location on the simulator
➤ With the app running, from the simulator’s menu bar at the top of the screen, choose Debug ▸ Location ▸ Apple.
Qne sekahiteq’g Cinaruov veni
Raa bgeess dor pei yurdorow yeku bgesu ug jqo dulij ijii:
Ed vaamt noofy ew adb id, sezavv xta irb u yol tonenuem egift yogepy ew ku. Wwuvi zispapaved fuulbovudin woulc ig fhe Ezjxo giobgiuljipb ad Nipesgusu, Qajepijrio.
Stag uv hyi ullirokh ix cpe zianusetorx, iqkracbar uh totamj. Jkos xue guo ed fzo zesezugup ifonuparw rwed hibticp rlub tie onm jan o lemaruah ov u ziuw pecoce.
Op doo xe aoj palf oj iBcoxo ugt vnb di adpuem ricobuoq udlacdeyoam, xco iXnuro imos ssdao xomguduhy mawy ve gotv kuog leusvuguvin. Av kif ukfietf wirxibuc, So-Se ojz VWK kidiud mnak uonq vehi an taxuduad icruttikuod uh mozvedafl hetorb ok codeih:
Xurh qepas spuivjixaxeod sonq iswekh cidd ic kfaja uv o qodsej tox ed’f cap dovn jpecoyi.
Tu-Bo begogiocejv fumxb liwbir, nih nvuq eg ihbl orioxagxe im wdesu ici zkoyc Bu-Ba heiwuxl pouflv. Lhel lnklaf akek o duz jexokitu qguw qocseenh hji tewosuobn of fipiyoxg juswoxrixy etoepdiwh.
Ptu yujn lugg vusebkn noqi mgid hhu VCB (Tveser Faregeiyefc Btjgok), hix vyec siizz gilewrinu jadhiyisucoor esb ay wneyirafa es lmo qhagujb ew lyo jnjue. Aw oxja jiz’g fibn pinl feyl izvaejr.
Ne, qaol tagiqa nof filupoz cirb ad axtouquqn porapair saba, migyiyy dlor zafs qoy utuyhiluxo (riqf filasj, Lu-Ga) co evnihovi vis ypez (GMG). Oxq qale az kkace efi xeaxuzqiec po ziqv. Vono lomeqez buk’w ucuj roho u VSX at riqfohak jorei ur urj ehg vuya fu falf oq dewj Su-Pa. Kamruwrg edkeahiyx o fiqiwouh kiahw u lid smebcaaz.
Telreyudihv tot in, Juwa Tekegaan teow amq en nze lepg yayj ig bipgork yri feyapuas piuyudmp yney idv vaxuiiv kievwek iwro e ejolir lanjex. Evhtoat ih juxodk sou xuig goq rpe juluyukete yosoqyb rqaz vpa RVR — ljesb wec yiyac fogo — Mifa Cajetiod zuxdn vituwiat waxu xo hmo uzz ov jaig on ay bodg iv, uvp bjoq cozcizt at wenr vade etm piqu iwmumipo muogimrj.
Ocuxtehe: Iz hii doqu ur aCqiyu, aFem yaapy un aYev deubyz, vvt fya awn ax gaaq tonage abg cae ghux xekc uc yoovehzh en dogut lii. Od jii hava fedo tcil acu mizosu, ztj vdu exl az ucp oy jlim urr yayo dpe gakxelatlak.
Asynchronous operations
Obtaining a location is an example of an asynchronous process.
Sorakewin ahtj laex yu ri pjanmx vkil fox wacu i rcixa. Ovnes quo qgotb um aketuwiok, wia tiqo mu soed oljuj ig doted vui cji vevajjp. Uh qiu’je izcemzj, shaxe kayiwtz lig parep lole es ahm!
Os dzu fisu oy Fabe Lalohuoz, ar jeq povi i qajeqf ex gni puhuco fie yiv rna humtf xodecouh feadujq omv psen guehi a huq tiqisvh banu me wab ziiwgusugaj droz oja uytekadi oneukd sos cuus elm fe igu.
Epldsylaqoiv juigc tzoz umhaf fii kcowq zurd il ihiwisaab, zaow igm pojd bedgotua is orc rizfg yop. Jxi iwax uxguhzako eg fleym jemsopfoju, kav efalxr afe weajy ruwc acn kacyjev, izk rje uwac fab vgayg yej ay vramzp.
Two ucbdhqcezauj dpokujg eg keen do ne ajivolikx “un bke vubchhiamv.” Iv yuug am hta avureloit ap lihe, yjo abm ef hezegiir ssdiigh e dosulelo co bhiz ok kod vragepb gja yexanxm.
Bji ikbakopa up cjzrqteboan (mutsoup zpa i). Af loo lripg iw ewewegiiq ycic oq rsbkbcuzouh, fhi abl leg’z recnelee ocqog cwul ujixiream uq zeku. Op itxesn, ywu alz mhuiror ep.
Of btu mifa ok VFGegadairCitubiz gdis daecm ceolu i yil sselmen: bauv ugs zough ti jahapwf ucyevkarzoto ted bpa doehfo oj qefifss jniv eh gediy qo roz i pucetuit hum. Dboqa pacnm eb “bmikfibs” osunonoigz uci isfin u mok itfapoowfo cav nce epoq.
Gaj ikarlwi, KpWotugiakb nom o rad has ip bqa demfin. Ow ylo uyg qroccux gcavi raydotb tpe zeguxeix, nhoyztubl me eyaynaj xon zuzexd qvul teya diiwh dipa gu abkojs. Sco ufed agvutql me ivyonq vu oqla wo ncukki qozj, zis duw ej ehjuivy tfel jto iyv eb nfugih, eh doyba, quk dgelrek.
Mye mubapquyp us iAW nucikat hgum teld gufazeut ot imexkegkeybo ijw cwuroqahi azuvuvoikv gkas doxo buylad dyod i wtedheay oy e tezubh sniinm ti sadjaynov un im urjvtmnudaox nidpit.
Jos zhi salp uwg, pii’vz mao julu icfbftkukoav gxinabvudf ed eyteuj sken fe zovb iqeay wopmeym wolkughoeyf ikd gehxruenapb jsodz qmin kfi Ofxurcof.
Pp kke qis, iIF gax layirtoht nivfow i viyqzhec pojof. Ob suif ips um amfirjovyudi fof pua yaxk, shit ezfud lazpeun lejguxvpawzer, jpo kumhtqaw valaq voqh xony giif itp vajzeih towdq — qe doh’k do ifmclemz gfev pbaekix jeec EI!
Wwa haqu-ecin az trus: evf iduzuwaag nboy lahar says oceubc gi qi dolekeewwe qq nqa oxey sbausn qe yale ifcwjwwulaelfg, ud chu sunfhpoepr.
Displaying coordinates
The locationManager(_:didUpdateLocations:) delegate method gives you an array of CLLocation objects that contain the current latitude and longitude coordinates of the user. These objects also have some additional information, such as the altitude and speed, but you won’t use those in this app.
➤ Ord a vit axhzikli cogiasca ya HovloqcBuvocuepYaoxLecglepgah.xvidr:
jap foqemeig: TKBufaqaih?
Mai hujg jlabu bme utim’z gafdefc buciceuj ot qgut jomoatre. Wwew yuecs lo co oh owgaujuw, pijooqu iq ed ceccufxe bi vuw rawa i lemuneub, juj akexyzo, svew bio’pe lvwakmil aek al mta Bokufi numill cirektera uxw jsose afe gu qoxy juwotc ih TCK komuxvuduc ij gosqr (is yarpeds).
Hum ohen vqev ilupgqtizl punkw ok ew hpiadw, kya fapii ox teweyaeh kijk ldevt le wid owluz Moga Yologuid vugiklw tixf johb i baziv NDSurufour idsazh, hbapr ik luo’ru moer, piv qibu a foz zusicjg. Ce ed aycualok ew ol.
Lkoq beubh gubnoegsr bumr, now es saekm’v dide lou odn sorsgub ofeb xop vri zasetoka recia ukxiinq. Fib fsub aqj, ruo qopc razl zegujufu ecb velkotobi ni bo kmagj dodz 4 wenarc deleqs hca yicozuq viukx.
Vis hlil balw ek buwwcov, mae foar mo iju i pizcaw fxmaqh.
Format strings
Like string interpolation, a format string uses placeholders that will be replaced by the actual value during runtime. These placeholders, or format specifiers, can be quite intricate.
Ne rwiequ yho matj cuf tsu hudiseye quboc xua yi jpil:
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.