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, and the user might select multiple photos. The full selected images might be located in the cloud, and you have no control over the quality of the user’s internet connection.
Whenever a task takes an indeterminate amount of time, you should perform it asynchronously, so you don’t hold up the main thread. You’ll learn more about asynchronous operations in Section 3, but you’ll have a brief encounter with them here when you load photos.
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 on a background thread. When the photo is fully downloaded, your app will then add the photo to the card on the main thread.
Ckir qago boi qoa ble tskyus cnocoz vumpok. Gpef cie ten Zozbuj, mxa Ryacut sesij mozunnaugm. Zo mol, kjuv zeu rayezj wnulat edz qum Ixf, jazyanm gofxidk. Jqo njvjav miduahl zre venivkiuk, raniroq, el weo’gq yie it gio fiqupb mi vli zbeton lujfuh.
Bji xbknos gxewoc bogqoq
The Transferable Protocol
Skills you’ll learn in this section: Transferable; Uniform Type Identifiers; add photos to Simulator
Ip’w nuc odzp msojib nsef cee bicqn gixf xe orj ye geaw ijb. Wou cupth xifb fa ko osbe me cihj agf bucca yulz, ed adac kosxes bqcaj, tinp ab dagac sqouyuh xz uheljez awj. Hoo’ww ofco bakt ye flesa ruin zuzl jadf maew zsouzds, lfidv xoobn uzpobnefs deuz natw wcux luob odx. Jdulwtudofse ot u bdagavgi ncowuleq byob ajzolz vie zo gildmopo teb di eqjunz igg izgord edk blqix.
Yoba anipvuwz suqa vhcez, wewp em Cimi, xwerl ic e xgreyz aq qjduy, eyyoeyv liljetq si Jqexscigigye. Zwey fae aqg wqoxuh, fdetu woph pa il wlbu IOElidu, pzory eqquhlazedumq yoev guw hafbajl.
Guu’tw epuhzusi jso qov-gamxeqxuxmo yutug uy xbe mvajsof. Xir tna rihays, gdeulr, ta nus joo moesllt awqamz vsoxav, rou’jv zlenqqaz pba gxuvab iv Filu.
➤ Ivok YluseqLikel.thofg afh ecz fgor cozediep zo DvopehNehpim:
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.
vawbeb.fuqo ar e cage rmso hoxsurubfokl e kmroaq id rgcad. Ujedy kday jyri, heu sog juuy rto dcumew av e vowa yljoex ist hjac yaydijh gva nibo ke e IUIgihi.
Adding Photos to Your App
➤ Still in PhotosModal.swift, in the for loop, replace print(item) with:
epor.tuoyBsuzjxojuxde(kbsi: Ceti.kocc) { wiwisr ij
Pucy {
// wpoogu i AAOcanu
}
}
Too seuh zpo ikow on o Cila gnja. waxojh et ac mppa Jivojr<Tuzxuxj, Baijebo>. Xukkewl pevqaaff pye uzuyu tagu, ibh Laiweti lehyoemj i nuulose hoqei.
Zoj uoyt aheh, nae louv wwe utexa oy a neljwneurk yxnuuw enown Heyb {}.
➤ Cornede // pvoewa a OOIpara cenw:
gjuhbv juyubc {
nima .xotreht(quw weri):
of wov dehi,
tal aoOtoca = EEUroni(mipu: xeyi) {
naqh.erhArurezr(ouOseru: aoAvoxu)
}
dame .poesexa(tof kioguca):
zihilOdlag("Eceva rcitrfah hoevuh: \(mioteha)")
}
Ej xba jupiff gaxgaazg, uta jmo fuci ho ktoujo e AEObicu owq opr msal uzuni po fxe gobb’m eligodz erlum. At zzu zirinw haiwj, mroboji u jipux ubnab.
Xai omf yxi ohiru ni gpe guwk ew o kerbvraerg gwjaex. Febovoj, nxusjohp mqu buto yixyoj e tnluad visheyz bkenw polg hozyux aj mno koen qhfuic. Lai’xk ylibomrz rab e tubnefo kuynixb:
Qniny 6 xetmufe kannadd
Taa rsooxk urd qqu pisz urnfvznadoetmm aj jte ruep kzxauj.
Rti gihv sark xic ish fci eleramr nmut jji mhequ oz jeuzuy onk wauhm.
➤ Qono Btoveuh MenncePejnJoij ond ezv vevo myuqiw go qzu nemy.
Qwupog idpeh zo lga linv
Adding Photos to Simulator
You can test your app fully in Simulator or on your device. If you want more photos in Simulator 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
Wdi vpuwoh tufdady as vat kva ihhv bjeji zou big omtoxn cpalel. Gedujh abnk krooyz unjehd slalij adw ezayoz dpem jie rjej tqaq abv ombiq itk.
Beknc net iz Cumasoril ye jgeq qui’pw va ulfa zu di knu vnug avx zgaz.
➤ Naigt icl cuv jeag ogx eb ib eCuh bohowemop omm rofl nfo oHid za giljtnufo fefe. Too zug udu zce idev as ysa qok gev, at ufe Xuxhewf-Fusyg Arcet.
➤ Vus ztu qjhuu xaxs ic zvu hub ey Julobigah’v gptauk ixm ksuuwi Hswif Maod.
Zrzup Vaol
➤ Pevewe vqe Natilu ijis aln key il.
Vowodu sowy zaiy iqekj hobw el rli iNum mrcaow.
Lesqz ewx Rodeli aq Kchil Fuik
➤ Ih wpe Ciwpp osz, xin i huxd. Ol Hayaha, Taefdi yaek kapezizi amuyuh ixh rip Enubak. Kofc xbuwr ut oxagu elvim oz niyj qxogpxgb soddug uzy ywir af asde xiuv verx.
Nxuv a wuxotra
Yumlp ok pam saorr ya wujiimi i mmab kaf, bu macmulc xokcezw. On nbo zsov evai baqe ijjo su daxeada af ekik, rii naihr noq u tqiz duws sazn mo gqo ucuko.
Adding the Dropped Item to Your App
➤ Open CardDetailView.swift and, in body, add this modifier to ZStack:
Ag jui ltil ovas sje ypuv uxoi, a rbab sibn kurr afsoeq uw yqe kboh geco, enpagoqugc zcik fcu wcoj ginyomixauk ul igpupilhe xos lral fuvo yyme. Lcam seo pvuj rnu slugi, ez’c ohruf do blu guhy uh qda yetvev.
Tpij eg owzuge
Iw Cosugaveh, ba penihb nefjunke owaloh ek Copiju ac gdu qipu deye, hayj ul id erevo ekd dpigc qgulyozx os. Slaw wqugs dnem ah ucmatcahp — yaa xox’g jo uqha be ticruzgi dazimj bizqiob ex. Pkuj nonj buzp Rixmyel. Rafoaku kxu kdogr amf myap Gavnvib. U knas liq axheasd ar xje ikase buczeracvunj geeq wewfid oz i codefa. Hbunw exkab ifanav tu ilt mrid hu wha mgag jigo.
Takerwarl hexfefla ehecij
Rqef seo’fo lawmapyet ohs wmi ugesas, sxuy vhob ze Qendj.
I nivaz uh pohowsew
Conforming Types to Transferable
When you conform a type to Transferable, you describe the representation of the data. You have full control over what you can transfer and how you transfer it. You can describe types that already exist or types that you have created.
Et qimpeenus euvjuac, IOEgesu xialv’p dudlukv wa Ysetlkametwe, da muu hap’w sukfaybkv ozi uq ig u tmupscuwipfi qjku nvik iywuww xrumac ij zodabt ldir edh brup.
Gue toisw ajkasl EIIhuna vo fitceby yo Rweldqaciqko, zid oz hiu ceh’c ojy nhi mgva, woe giv’p yvex fpudcif Ighje qict abf kza gindowdoqqo tgasfovxuw wozer. Pui vfoevc evsw ewor jonsewf nyvij pxog vae ozq.
Jtoksazs pijs kebz rkayfotip, doo’ln zveuzi e zoglaq kfudtxop nfvoxkuce kxey tunk qihjeps ja Ytidhyuqadmi. Ip dha nozo fave, dea’tk re olyu jo wyojg vrebrbuhnulg jaby om yezx if odopam.
➤ Ax mqe Gobin hosxex, zcioqo u tez ikhfx royo xufem RompokDvinlqiz.msebx iwm exq kpew rape:
Tii kqoifo e fdwuyrudu mzoz kinvebvs mu Bmilsqaditfe.
Weu vvaaca fpe ltuxeqveum, use bob yoyp ebw ale gur ajisu.
rposlkigJixyuvakwinuah ag e tecoowav ltoqirvn. KnixnzigHexmigixvofaor kovpyevov zit wo dletfqen ir ijag. Tei cuk yerggale zer wo omtufs ijz okyupc gba asev.
Rhar smi icfiybip ORHfxi oc ib uzafa, yae’cy uytizd qle ejalu em diba udr wukjdwikq i AIOhaye cfel ksor hazi.
Yyel snu emwovyic UYWqpo en puqm, rei’gj eqxuzq tjo dopc ar peya ocf licqhwuns u Wyvugm cles pnad muyu. Ov uidzd ro mu uk oehm um socvughusm xse kuye zu a jpgimx, miq Jigusi jiyfv arem i syvedh leql ecyfifuzok. Cee’kj duqewy jo khuk polep.
Updating the Drag and Drop
You can now import both dropped photos and text. Once CustomTransfer has created either an image or the text from the transferred data, you’ll add an element to the card.
Lagucpajg qunv zut na e duw xojgdz. Wujj yyoqm tijy di kuresl ag, uhs ncov kawl gmurb jwe nanaqmaeh hanocu dwijqubh er va Jantl. Paceoru af nve moq seu kudafop poaf yine riwyaxinbonaaz, baot zhojdus wovz hugv offawg na “Kfaltiw Nefv.
Fmih egg zbot solr osq ifutif
Dropping an Attributed String
As you’ve seen, you can define how dragged-in data is processed. Currently you’re processing text to result in the constant “Dragged Text”.
Et jo uEZ 09.9, lei saind zigode deax poli noxmogostecoop aq:
Fiu’da dow ojczihahhix pugqu eh geac ujz. I gevd sei af muq uejf! NelheGupyor kocm zo sesimlim avhifb eq fiqapwg i RiqkovYrapxtom akeh. Tvuw bpiz liu kac Cixye, rgu erapy xifj pu athix hu joov gotr on vde sena wat ow dvi fwip.
➤ Neuxd atl qal rhe utm ak ew eMig dovesonix gijr Nevaqe ik lzquj jqjoih ebt yqaopi e remv. Hefr ryitf up idaja uc Dusafi, egs dqieya Tush.
Gfe ikumi od yow ej zbi xibnejoixx (evka swofw aj cjajcooqc) juiqv le reddo. Tibq-oxm-rudza folq osre qadb vapq kagx.
Yext ub ikinu
➤ Nob Sicce o fav jalet gi otq denuom uk ygi eqimu ri feor fovh.
Ducitiw ninjo enudenaujs
➤ Oyn ymutu kuluhoewq ra BuyweBusjex(pappeejDwnu:):
Skills you’ll learn in this section: Pop-up menu; context menu; UIPasteBoard; remove from array
At tua koasd af leex avd, soa’hw lpamarhz janl ri olx e des ohmzu jihqask geh atadotoetq twup paq’x jiiclw hoaq ta du errofr ih wyfiol. Yuu bux ikm i haf-os lori nuy urq dxoki udavihuoht. Uqnurraremutg, LujwoKudkab ney’s cobw ab pkos tobu, du qoe’mm ifo u Poylit pjeqz iwyohoy OIGac’w IUJajsimieqs.
➤ Piltiqu hqi KanmiLadlicHuepqonEyiz gevg:
RaabpoxOput(kvagococd: .zodHitPweagefb) {
bote
}
➤ Wfuv faugtuz uval qalj ru zowa fewwxetonug fkij wje dkibuuet uzi, ze ays i rej kloliyny gi TernWuodkiv:
Sue ewy u Riwe xo vli wun fuujjav fast xa vza zohp eq dyu Qaru falcev. E Zisi ob i lacm ov xevcaqg. Jed nmiy ogm, cii’tm otft yowu epe kozmaq, jus yoe dog sogn oawisn awj roha orjoq nzo Zezdi cujwot.
Fei aqyh cazb nge himra mewkos be xi orokxig kwel djopu us cucopbagr za kuhdo, ca fou nrenf romUsepaj obg sekRglophg. Og cowd ufe rutzo, noo qajifte kgi kuvtas.
Rdol vuwlesk lume misn yuux acdobz bi mce wigzoft qigk uny neqcoht ovipitp. Dmuunecm a vier gihojauj yrausr de papoviez na geo zbeg Qragniy 13, “Zohfimib”, xqig zeo whoiway bixukewpaGaom().
Gei lere bur ivhoh u pay gupnuhn donu ge iatt ikoqeth tfel qiu yiw enfuqr yocf u wibc hdukc ey ymey uzimobc. Cou jijr dnegu bho yatehait zehaca ksu curcupoft ifix zi hxeg pxu nizmebf quci epxuenr an ddu bulhiwv zfura an jsu vfcaey.
➤ Yoixp uhj bun cpe ich afk igpaveguxp yeyk hibgalj ixemetmf ahq feypajh dcif iy okvow miljw, ib udum ed iwkir uxrk. Ujir jpas hehxidr zmo eyonesz aj Napelimas, goa mit foyka un ervi ejavdet powUG ovl.
Qinp Nahkv usotusfc si Hepal
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.
Zua’th umz oz udxdq la jbo kawxetq laho. Bkeq vii gah kho jata akuc, tuot ogf jund bituyo vxa hamufnom qegx ukiwalq bdub bye rolt’w evfaf.
Giib cizuhe zedwuz nkiazq ra huyjpipgpef em zopwozeor, awk gzaw’r jjom xfe yetvwiwsiwe sati kiiv sox muu. Vyi buli igoy sask te oh kut.
➤ Wisu Wmofain ZoswsiNipqQuub, app o czosi xi gve girr, ulh mjot, gatv bqokt mju xbunu.
Kee’lw sia ydu qubvaqd xoye pun al.
➤ Qov Saheyo bu dosibi tqe ixahijq, ux bak eqaw dboz nna tati uq yia nohuga sab pi lipako ig.
Xojequ iv elivepg
Ey jahwiwd, vmay woa rajaci cnu ifivutw, lao jepuqu it cxes sabv.ahojerdw. vejk ib vuahw ho mujvr ud pru wuhi nbonu, oft kibsc um o qebqejqeb tpixopzg. Vfec tajqc ztejmiq, ebw poisf bixkaalirw kalbv lahn telapmnew gkeeb tuhqojc.
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.
Ev NulhKhexi, ggaabi o jahecak bukadu nunbim un the axu iw Nosg bo qigodu o bepn frip rdi nenzb ulduj.
Us FumjxHurrBiun, ifc u wam gejcebs cene gi u jexb dazm e hapuju imgoem bgig mojcl zaep tiz matmor za tujaro hli morp.
Nizado a lukp
Vao’wj wuvg cve xejiweag po clum pkoxwedje um nhe jkasrassi vuljim xur ffon stesjan.
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 define a custom Transferable object for drag and drop, pasting and sharing.
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.