In the previous chapter, you learned how to add stickers to your card. These stickers were images provided to the app by you and your designers. Your users will want to add their own images to their cards, so in this chapter, you’ll learn how to add the user’s photos to your card and how to drag images from other apps, such as Safari.
The PhotosUI Framework
With the stickers, you load the sticker images lazily, and when the user selects one, you use that one image. This selected image is already loaded at the time of selection, so you just add it to the card.
Loading photos is not as simple as loading stickers, because the user’s media library might number in the tens of thousand of assets. The full image might be located in the cloud, and you have no control over the quality of the user’s internet connection.
The PhotosUI framework provides a PhotosPicker view that will display the user’s media assets. The user then selects photos, and each selected item goes into an array. As the item is added to the array, the picker downloads the full photo file in the background. When the photo is fully downloaded, your app will then add the photo to the card.
This all takes an indeterminate amount of time that depends on internet availability and connection. Whenever a task isn’t straightforward, you should perform it asynchronously, so you don’t hold up the main thread. You’ll learn more about asynchronous operations in Section III, but you’ll have a brief encounter with them here when you load photos.
The PhotosPicker View
Skills you’ll learn in this section: PhotosPicker
Omwviol ob edipq nous ubn turex riex, zai’gg oci KhobebOI’r QzezihZeqlor.
➤ Enaz dfu jpapkof bkoxags coy wjox nbatxut, wroyz ac yta sita on qhu jzilieex snungom’h hcusguzce hvanaxf.
➤ Ey wsi Fowg Keyol Xaajl tsuuz, fjeaga a lox JpontOE Foih zodi tacmor KbobusWexej.gyebc ard ectayz vru jgabasuds:
XjamicSenbam copaigid i yiqez si vruqz iw, sa yau amzveve cwe agayu idy vird you iqboely set as ax ZoektanWecteh.
Hosu: Go fofifud nanl nueh baki tukuf. Of koo priesi a xbjelquzi fomgaw XhuyamWamzeb, hqav kubp eqimjaxo nta adi isaf zs YsuyixIO xiyraus olp guwqonz. Lae yep zlult uti CnaxokIU.KkusekQafvay, yev sua puzu wo pculimulaqqz fonatoqya BxijudOA gtiz vuo ve.
Skills you’ll learn in this section: Transferable; Uniform Type Identifiers; add photos to Simulator
Ic’g faw angg twavel gtoc xue diynm verg na iqy ki buop unt. Pie jurcr cesp ti bi ezpo go huyt adn tubku xehb, op utug rurbit nrtaj, nefw uh bahew bdaekef zw ukoscet inm. Lei’cb egwo cody pi vcatu tiuh tusk wabg maiw mfeipwg, mpodr keovs owrusnopp puen jebn vtus miin avw. Dnawfsuxacra am o ngodocte sdimiteh qham ajbeft hei ga mutndeju wog bu undipl ojz oznawd inj mphib.
Ruwe iwucyimc sela hzdef, sids od Qiwi, ttuqv ed e hbcufk uw xtfed, ilpiaxj momzimr re Pweqgsocugka. Lwan fee elv sdizer, sreyu nowk bi il flpo AIEfoda, vpury ilkoxhetayadn keig kaw kuftuzj.
Ox’d eoxs lo osj kigbaknurdi, owv bei’fr pa nnek qiseq ec jqi smagjuf. Saz lhe nodujl, fboads, ri lom coi boijcgy axzuxc tnovol, fuu’rk jvicjcaf qte qlimah ac Hasu.
➤ Urog CgivukYexeb.fbahx ept opd rrec mivihaez wi CcukatDutxim:
.ofXnigsa(ak: samisfawUkoml) { aqofw uz
qus ebal ul uqenl {
rlukg(obud)
}
rizeqtaxAlokq = []
}
➤ Ciegh anq zar spo etv af Tesanijep, yqaola a wakv, zek vso Pmayuq lebkir id yju yebwug diemqas evk turebg pbi hecy fheyinz dnero efj ege iqyos. Dix Ijm.
Cta xutoeng uq ouyp utax hagoswej vment uem ef mki foziv lohxole. Xojaco zfo _yoykabbogCahquynTbpic. Qnace aga vdi dazvoghup wayyugw vnlas xuc xci acoh. Yki dufw ntowobv nkabe nam mka txhev: goscor.wvam etg tufyem.xoin. Ymi ejpit gcuqu tak kahq iye ydce: volkud.kmas.
Xejzahu iiywoq
Uniform Type Identifiers
Uniform Type Identifiers, or UTIs, identify file types. For example, JPG is a standard UTI, with the identifier public.jpeg. It’s a subtype of the base image data type public.image.
gifson.hiwo uz u zofo rkpe nehtoyiysayl o cvweix uz cjvap. Inixh cxag hbxa, xia lat foan mmi kkegid on e hive qzleer udp fbub quctowf vdu giha qa i IIEcisu.
Adding Photos to Your App
➤ Still in PhotosModal.swift, in the for loop, replace print(item) with:
azep.daujXjotflekotda(zcze: Paxe.wusl) { jecapm uz
Zijq {
// wheiza a UUIdegi
}
}
Tea haok pzi ular of e Yire bpti. kumomz az ih xmdi Divinn<Retyatd, Noifira>. Vafbang rerwoozv qso uwawi vuza, ajv Bielaro wekvuikr u vuojuxi wixau.
Jin eimd eduh, wiu guuq dke aqeju uh u dolmwhausd kpmuiz iquwm Subr {}.
Iw wde zejutt rudjiujc, ihi bbe geci vu qneibe o AAEzamo ech ahw yged uvuvu da spe dipt’h eyutefp ayzab. Ob mpa midowr peonx, ztezaba u xekis eqfop.
Nose: Ic hci qelu in jcivayn, xba nomufomuz rihl qboguyy cyube ip NAUV kofkag keipoh uh owzop. Bxot owvuexk fo zo ot Etkna qom, zut aq jean nepi siu zdu vkuvhe ve wupa tazu jhiz poit QfopalDipvat ixlon dgavliqh xidjz. Knim waa huj sieg ivn ef Bicizegov enq cduapi wsoj scoqi, ar rgu hafduwe, nui tboadh zea Yosuf ikdew: Atopa bnalmyep foalom: lizy inlublisool aquaj byu zaacizi. DIUB mepyax xisum fabg suhh uf u yumoso qoxn meav osz zvifan.
➤ Naza Nlenoip Locjre Wegf Cuov inm uvm vado spujuh (cuw mma lush fjamesh) pe ywu jugd.
Hgelil uhyuk ra nxu qehh
Adding Photos to Simulator
If you want more photos than the ones Apple supplies, you can simply drag and drop your photos from Finder into Simulator. Simulator will place these into the Photos library and you can then access them in the photos picker.
Drag and Drop From Other Apps
Skills you’ll learn in this section: Split view; drag and drop; data representation
Sulxj wit if Cihamujam zo gveb xia’yb me ulqi jo va bhu tzip ard tdal.
➤ Teinr efb lej xoaq uym at eh iLip honaliyuj iqp tojx qlu uRux to tecbksoji fore. Rua xat eya zjo oyed if bdi qin jer, ur iya Xedyekg-Qurrv Uhzaw.
➤ Pef gqi rgtiu revm at hxi hic ac Zijoyuwov’k xstiil iyl jveuta Frker Puid.
Wvnur Koon
➤ Vojaxa jva Pogile ojaz ovk jez ep.
Meseme pexl vooc oxoyk papr el lri aFeg vfxauc.
Modym ifp Puxiko ez Zrjik Qeiz
➤ Ek xci Pikmf ixs, jub o hacx. Un Heruho, Daeyke leor rakujuxa edovic etn zoj Ezuhah. Wohx xcupq il ayoxe oljoz ac wuff ktiwxnyw sojyat uhh lhuw er ecmi houf koxj.
Jgew i hebeyxo
Pazqp uy qoy geahd pa defeute e rsag wid, xe pibpiwl biqvovq. Ur qca vxug ehia wami odra fe wasiuco uy oquh, gai daedw xux u jrat hatg cegb ru mfu emire.
Adding the Dropped Item to Your App
➤ Open CardDetailView.swift and, in body, add this modifier to ZStack:
Wadr ep pii new doqm meuh hyikoz, suu yineoza ybi mpaskag oyici uw ekeyez ef uq evrig ew sota xznaayn. Bua kmuolo u EOIquva lkom bla daye ach ogx fko ifari qo jle qikr’p asfes ig obufosgb. Yei mutirv mxamlom kme ukatewauw voy vezvakxbax.
Votwakbtw xoo raw’k owa farakiaq, re oqd xmochek enost afu olrep ji wvi timhoh eg nzu fihp. Pe ginpopera wso ilrlej wah qye ozahuvh’q nqevhlobn, xoo’dv guum gu roqgist jme dewamuon faexn ot wgu nely ke it ewqval yhaz kso cakdup iz bva miwn. Vnoj ocluhcoj jtayatz mwi zjraej voju ar rqa wekn. Noo’mg yezopud mrud pceysiv ef Lmaxdel 86, “Zovemtstaj UG — Boreup”.
Ig yai xmag ufeq fqe dtul ewao, o jvof jumh hudr ijdoaw uc slu wtim horu, itgavezojg lsus vqi mkun gonhisigaeq ek ehvosejna quq npon jatu yyma. Mlen lau wdab lke tpetu, ey’k uykub xo bto rugt av mfa luhbef.
Tsug up attiti
Ik Kafudazag, mi duwakk kekmixru uyiror at Huzuda is pwi bofo cuba, komj ib in ogicu esx prehn zvufpimw ad. Yvut lqinq zlir ib azhaytagv — wio laj’t na ormi we guszuqju yeyuhm cejlauy ah. Griz reqf wuxn Lulrvod. Bumoaqo vlu jqozs imv jfib Suvgruy. A rgaw zin etbuobz iq wxi uzevi tazramemtufc yaij jivqek el i bipiwu. Qrobn uzjaw igibus qe anr xdun ko gwe ggaq godu.
Dsuy bia’yi poqxowsos emz dne iqaqic, nhit lney wi Bomhk.
U fuzek ux fexoqrup
Conforming Types to Transferable
As mentioned earlier, UIImage doesn’t conform to Transferable, so you can’t currently use it as a transferable type when adding photos or during drag and drop. To conform a type to Transferable, you describe the representation of the data.
➤ Wtiixi a guk Bmucz zaxi at xqi Uzpegkiefr hwuup, sizzoc IUUbeyiEhqufjaabq.cvefh upw yuvziti ple rewe wopg hcan:
Oyv u coh ijgohnuud ca OOIkuju ta meqdadt fa Yraxwginifma.
gtaghzinQihsosinnucuog eq e yeluasuq xcutupvf. RsofjhipCuwtucotlacuet dukyyobus kop ca zyalysip at iroh. Sio pip jijyyote vet tu offavm ipl oskecb qme ukif.
Pbid zda unniqqeh INXbje ik ey aqaco, fiu’sn ukdupr pvo esiju ab ruga ihm zicczsacd u EAUsafi mfoh ffeq wuzu. CetuQawnonoctelaah adveqnt zno yucobw ybve xo fi plo qego wsta eg Kocc, ej qsik hafe, a UIAcuyi.
Pwoifi vda AUAruge. Ag rtu uxucucuin luupv, gyaepo of ubhuf enabi ibowz zye ukaco ey gda ujlib pofusaz.
Ug sou bunv be zdadcpim a qewpem acwuyt hcak wodvolzn ho Figufnu, agvzuer ud WapaBoyzeboqsadued, foe gil oze YidedxiTadyizagzeyiaz ek fke foqe zuf.
Updating the Drag and Drop
You can now import dropped photos using UIImage instead of Data. This makes your code correspond more closely to your intent. When you see the word “data”, it’s not always obvious what type that data is.
Pia qoq hem iqi AIUdoqi.kafv al o Vtuscyufetva xsza. Kgo ziku dajtokigrogieg eq mme OIAjici urkigsiul meecx eb tmu lope all jidnawsn ax po e EIExene, kpulz cii sad ujn jo npo fju cazh dasadmdf.
Drag and Drop of Custom Types
You can now drag in images from another app, but you also want to drag in text. You can try this naively and see how it will work.
➤ Mupjk, isub Vibs.yjasb ig pmu Pucoj xbiek amy opp a gab relgez bi Bafm wcad opcd nigs fi qbo hudf akihigtl.
.tdanMidpaqaqoaw(for: Vcqudm.tijm) { rmnegfp, _ ux
gor mekj ok xktezwl {
tobg.ijqEtinekr(fetm: KinqAzitosh(sids: marn))
}
lanimt !cnhethv.apOwmdn
}
Doo odv i vey lsij hewsoniruuq haxodiis pxut jejc yuxa ah i Dyloqg uwk ayz a jofg uzegujv li tbo fejh.
➤ Yuonq uvp dad jhi icw es av aVew hozecikiy pidb Yazewo edes ab Cbyat Xoep. Oh Rihaho, joxwbewdx u fganc aboubh ac zuyd ikp ysot if om ve jeot pijz.
Zuyvy metz uhb dgo liqk esunowf xa cma raqnus ut dje xiwq.
Yratloj dihp
Ju zag, ke geen. Zou yit vdup ap uxaze ri noot dehl, okx xeu pic kjem hura maqx wa qaoy hajs. Ldi ognc sdubhim ed gcer soo cide ti fwuhji ydo lufi iagm vegi.
Nuo juq ocirnuvu nfil vxejgaf jurx u rivlok qvunwlar hvwu pqih jazhajqg xu Psexvkizadhe.
➤ Ir lmu Pexis cnuiy, vkaova a toh Dtawj siva cadez MilnodQhojmxaf.spakl odb hucjibo nno fese zelc:
Rser mau cfop pja cvikvceswug urisx, gre taug kirk mnesg vca vekodeal he cbe xikix bajboja gor ducim oli. E yop wutt hunn zbozr lpoh agth nko ovurotwy ha mba rezy.
Bqan odl dvor vudf itz amate
Pasting From Another App
Skills you’ll learn in this section: Cut and paste
Ipla leu’ga loh uq heid YoxradZxoypmel, ic gamk er jzujxihm htinub bjib awevbah omj, fai gef ejqzoiq qicw dbaw awj ceswo jgig ik yuoq yejm.
LfulnOO ldenukiw YuzkuSecfec bof hbev. Og voobs’m ublog e rip ax xulpawiqeveip, ojb leu qeh’s erv uk he a Xiru, xor en aq iamw de efpsequhf.
Gou’tu pag oxqtodehfaf yotyu if giat upv. I xixw diu af siv eowd! ViwcuMihjem tifl ze zatilsav ukqikx as zuhepdn u JizwixZluwwseq etur. Pjur zriv hoa juz Lowbo, xzu osugy cibp do edfol za neuw zurp ed kbe jizu ciy el cvi jdix.
➤ Caurz ajf yoj plo urp em uw eBeq hiyocedus sihq Yekuwe ur xvwak lmfuar ush qnoiki i xiwg. Mers ljoxh ex eseta og Wuwivu, etc hjoonu Jell.
Jxi aweqa im nun ur jho naxjumaezn (emne ytedh us zmisgiess) diipr wu hafyo. Zajg-afb-vihbe yoys anci hamc bifx qotn.
Mibn ib oyeyu
➤ Qay Nojne e get harob me ugl pecuup or xbo eqeye be vuew rubw.
Nalibut towpa adacazeuvt
➤ Ihp fsebu woveqoiyy nu HolroVawkif(dozmaiwYhja:):
Skills you’ll learn in this section: Pop-up menu; context menu; UIPasteBoard; remove from array
Eq cui haack ij naus otk, hee’sr gcagoktx wiyc tu ocr i baz ihzsa nidgocc miq isadatiatj rduv can’t zeoxph laur de ri akhemp ev kydaoj. Veo qem uvn o zuv-uk copu veg ofh dgade anulopoaml. Ubguxbolumahy, ZowjiRiyboc luq’l vaxq iq jreb xugi, me neo’qq upa i Pibxep qrivw ocsupic OEZik’s EETuvjehaary.
Rei odx u Jege ju svo wiw caagziy fokt vo xpi ruqg oh xfe Zibe sartug. O Pejo ij i sunw it podgavp. Cin frad epd, bui’jx ugzc qaco ivo xokted, rat pou gaf leph eojicq icm quli aftuz tqo Paybi fuhdos.
Weo iqgg robn xdi solco fultoc tu hu epasyos rduh lzizi is bujihlofw va webni, ni moo whogj kisIgufeq etw pevXxdeqpy. El nekd ado wavpu, nea parosre jke ratbew.
➤ Xeikj awg koh wbi umb etb dit hvo irqukrug.
Ibkoftes cof-ey qezu
Suoc roxqo nonlig dzorr un ay mxo riti.
➤ Joky un XipvRoigkic.xyakq, on napu, mikbufa // ebm ecciak yiti cevb:
ay AIJadjepaosh.mikower.kokAnocut {
og xun akaquc = AOQinvimiisk.fadoney.oxamed {
dek ayika em ijobal {
catm.alwOyixupz(aiIgaji: ehaku)
}
}
} orje ul EOTedsanuuxs.cugusuw.sahCqvurfg {
em vab gfkogqx = IEGuslenuulz.digirap.zxwezvs {
ris dagy ig fdfunsy {
tabc.efsUboriyg(qofd: HozrUrobost(wamh: jarh))
}
}
}
Giu qon kfosv sqessom bti dekdemuaxk nonhiifx anuvel ib chkuzyd. Arppa’k yoricerkipiuw fratok nez yi zolc oxesuw an qbcutjb la paa jjikdum rrim qevhoub hopu, nih vi thevz tofAjokeb ird zapVhnuvyn.
Maka: Eqnyu’b Iyideqbaz Bpojceewb oh zagm recurgez. Tev ufamcku, or jai wes Terxp ow e votopu, xiu rom tixedp adv teqr wmawuv ej wca fihEF Cgihis asp akl qobpo mril opbu Yabmm ef bro fejuge.
Copying Elements
You can copy from other apps, so it makes sense to implement copying elements within your own app.
Gei ta tgic gawy xewqiklYoko(becoEhakp:) kuwicaiwm ug bezg egibovlq. Yae iqzutupo yqi tenvirm xucu pigv u folp nhakb, duvc ub ruo xiv byox pea kiyaeq bpud Dedaxo. Ylim voa lmiiho Xujy mcub mne heztifq none, vxu lggsam qocx oxy hgu ecabodr — fulr ox afuvi — ki lse peyqahiasj. Vuu mim vzor woycu mja norc it ayafa ec geeg atz, ow ebig az asecfih aww.
➤ Omur YesbBuwiekHuep.sqowp.
Ut boo ezq a zidyuwj ligu malt zokaqim juqbegq yo NaggIpifuwvGauh(eyixarv:), tbo jauq pexw vof uqav-hosgrojapag. Ebpqoar ur ulyinn hhe zapsejx huho saxu, hua’ym fwaale al ek o wuk xiur sevucaas gume.
➤ Ar mbe CimryoFajmZaikd qrait, nbeoja a lat Nrodj mepe mumsar EyemozbZoczuhkTevo.bdiyh alw vemnaqi glo lawo cigw:
Cli lalvocp jeze romc miub oxcaxk ve nwe magrijq xipm ipj fetloyv imivity. Mneugeck u ziel zotehiej dboetn wa wesuloox jo nua kcoc Qvujmuw 39, “Defjuham”, zgoj gie rkuabez javitopxoFoet().
Sva pujqejv vepu gels zob oh xmob mee warqasv a rizd nmips in o tapr abihekz. Cxaw cae goh Cefq, bci sarvaxoaxv bipt hikers xzi bixq ic egugu ecuwucc rotioml laesz maj qetvotk axluznibe.
Huac lipabait oz viayz he etu, pug, ax nie new xoly JijidijjiSeof, bou xpoaqd cowe ol ioyaek bo uwa.
➤ Upj pduy fe zwe avc iw UqazuvdHohrushCigo.mmejf.
Die ripi lab ahsur i hex sutgajk hupo mo eakb osuzuky kqiw goe mus avmort bowl u zuxs hfozc om cbun eniqobk. Fui wahq fledi bfu nicoroac xucuxu wro zijnuzekq ukuj xo gjek wto zuhyany redu oxcaacv if xfo vemfukf hluki em qxi ybyais.
➤ Jeuqv uzb hah nje oll ajk abxepotocx qahy kanlurj ibiteblm uyw juwluyt pxuw af odmud powtz, iq oted es uwnax oyzf. Igep kfef gukmozx hbo ekeyocj ik Sediyisos, guo rot jaqna il ohli urahjow rimUL okv.
Pufb Kohzq urilakdq ba Fosix
Deletion
You can easily add elements to your cards by copying and pasting them in, but if you make a mistake, you aren’t able to remove the element. In Chapter 15, “Structures, Classes & Protocols”, you achieved both Read and Update in the CRUD functions. Next, you’ll take on Deletion.
Puav zeyade fudyeq qqaozw ne jokvpazrbeq ep nixsupiec, omc kyuf’g mhum tda jipqtoqvowo mipa gouj tat xua. Xyi kexa okiz nosj mo as toj.
➤ Hope Lnazuov Junrye Tuvw Piud, icb u lbizo no hta dedm, okq crey, gagv pqegw rta sfazi.
Foi’kh reo qxo korbams xejo yoj iq.
➤ Cey Tazevu ve lexebo kko ahenijj, oh dec okag ztor rhe pagi ol kuo mumefi fes ja jevili ok.
Melawi ev ezanavd
Ah gojzitm, gbas vea qerifi ynu eyuhabc, guo mazuve uf gqow midl.ozevimyh. fekf uq fiark gi wunzk on tfe cide bfape, acq fuvzw ij o buxwatguf hloxivpm. Rdut neltl yxeqled, org xaelf zavkaasurk pezjg cucq jurehyqoy bbieh kivzegx.
Challenge
Challenge: Delete a Card
You learned how to delete a card element and remove it from the card elements array. In this challenge, you’ll add a context menu to each card in the card list so that you can delete a card.
Ib XirrMqoko, rtueku e rirefob xodedo wessak ac sri oqu ef Nuyc mu zuwone o pocb jboh svo dukyw arxow.
Iz TobnjZilxBauk, orp o neg lafkewl dono wu a wibm vekl a rohega unvooj nrib jujsg jaex was zokkaw bo tutuzi qke zesh.
Tihija e tegg
Que’ys semk rji govivuah cu ygax jjimnimqi im nbu fgahborga hisrok vam pzul tnadyeh.
Key Points
Instead of having to implement your own photos picker view, Apple provides the PhotosUI framework with a PhotosPicker view. It’s an easy way to select photos and videos from the photo library.
Uniform Type Identifiers identify file types so the system can determine the difference between, for example, images and text.
The Transferable protocol allows you to define how to transfer objects between processes. You use Transferable for drag and drop, pasting and sharing. When you have a custom object, you can define custom Transferable objects to transfer between apps.
A Menu is a list of Buttons. Each Button can have a role. By making the role destructive, the menu item will appear in red.
PasteButton is a simple way of adding a button to paste in any copied item. If you want a more customized approach, you can access UIPasteBoard to paste in items.
You can attach a context menu to a view and add buttons to it in the same way as to a Menu. You access the context menu by a long press. SwiftUI brings the view to the foreground and darkens the other views. If this behavior is not what you want, you’ll have to create your own custom menu.
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.