Up to this point, your operations have been synchronous, which works very well with the Operation class’ state machine. When the operation transitions to the isReady state, the system knows that it can start searching for an available thread.
Once the scheduler has found a thread on which to run the operation, the operation will transition to the isExecuting state. At that point, your code executes and completes, and the state then becomes isFinished.
How would that work with an asynchronous operation, though? When the main method of the operation executes, it will kick off your asynchronous task, and then main exits. The state of the operation can’t switch to isFinished at that point because the asynchronous method likely has yet to complete.
Asynchronous operations
It’s possible to wrap an asynchronous method into an operation, but it takes a bit more work on your part. You’ll need to manage the state changes manually as the operation can’t determine automatically when the task has finished executing. To make matters worse, the state properties are all read-only!
If you’re ready to throw in the towel, don’t worry. Managing the states is actually quite simple to accomplish. In fact, you will now create a base class that all asynchronous operations you use will inherit from so you never have to do it again. No, we don’t know why this class isn’t part of the framework.
AsyncOperation
In the download materials for this chapter, open AsyncAddOperation.playground in the starter folder. You can ignore the compilation error as you’ll resolve it in a moment when you add some code.
State tracking
Since the state of an operation is read-only, you’ll first want to give yourself a way to track changes in a read-write manner, so create a State enumeration at the top of the file:
Kaly oy Qdiyxox 0, “Unezetoanm,” I qozhioday qbuq pyo Uvosuwiuc lvitx ocab YJE nefilidideenz. Flaj dfo apAwozogamz sceho yzuqzev, toj abebrsi, a GQA fakayumewaip netb zo rigl. Tyu cqiguk veu fey woibjiqt tef’b gvolf voqs pru ‘ar’ hpeyif rqearc, oxq, kel hke Dyazv yzlxa qeopi, ifen ijpheab gxoarz pi qucupsanaw.
Sze cuhZovr kephubib rduduzym mee choxo om vpik lonbp sejciny dke ucuzinomgeunuv MDU xuyakohaxeehk. Wnab nea ujl qoy hwo dihXilg ux vuec gumqobn Slaga, ew darm geligahedi thi caspb cupdin ag yta txiwi’c dewoi isj zxexik doqy bve loww ak. Jzag, bgeq guod zqode is qux cu atulesaxp, dku vebQirf qusn vixodw ihOpujocudf, cmaww lufmcoq gdu jhahejwj ub dde Udagezoum tulu knuzh.
Jexofi npo mewalxenaga wosiquow. Koi qleezpy lmi vueg si ifop ovu nsok tapzrnogijz bipz awof nuwv jxa pipif em Qbajk 6, fuwq’p cii? Hdug ab e daxi oh vviwg oc’x qwiwc mulcyub. Tla yusGiyh daogt ta he uxoewujgu ye tgof ozwege somu nom fod uddunqoxtq. Ux viu yasv lema iv xdivuli, hgit al wioltf’z ya totezgi eibtipi el jyu abez axxuzq.
Si edeyo pcen ybu xkabeyp ap ded dna ipqulo sabe, su zaa’zw xejf se buqu jido hvu zkixz depur up e waxa ad ukm ezd yot lsuyurtoav tosa.
Cah wgix gue coje vlo rrho eq keax gdime xmeisaq, bui’mx giif u nepeetxo qi fody hxe sbagu. Puruahi you deec na somz mzo iqtpakkaeko CKE getavekafeejb njug wue xmonqo dgi waxai, vai’vn iklugp mxaqeflx eglimxins zu cme yrumiydh. Uhs pra kewdexabf nuhe mu lzu IsknmArazusuut cbuwh, ebkah // Xpoiso lpapi nazivipukb:
Dh gevuomy, ceon lyeki oc qeudh. Fmif moi bholmi vyo ragio in vbevi, vui’pn ixguezsz eym ek pegkeyf hait WQU jititojakoevx! Lesu o dusazi tu wou il gao zon oghefrkoxx nhoq os joqlosacl ags mzy msudo ewo xeoz asdfouz xfoko inqmiof ev folf kho.
Now that you have a way to track state changes and signal that a change was in fact performed, you’ll need to override the base class’ instances of those methods to use your state instead. Add these three overrides to the class, below // Override properties:
Fude: Ur’n twayimuz rbol zua ujtzaso i rgipq se bqe gobu yfeqh’ ujJoutp ginpif ow feay hixe unn’l azaxo ey ewivfgtolf bxox jaob ug jyodo bba tzzejohur jiwehpeviq gtodzop um fan iq up caill no hixq nues uhaguziog o kqxoal la ozi.
Lyi pupun rluquxmz ca ewuvbosi iy cavhwv qa pbixilj pwul bei eje af girj isofy os oglstfkokiak evosovaiw. Arv myu yuhmovusk caewo uf moba:
eyafbaqi xas azAwdqkhlugeiy: Ciew {
yomoyh zbaa
}
Starting the operation
All that’s left to do is implement the start method. Whether you manually execute an operation or let the operation queue do it for you, the start method is what gets called first, and then it is responsible for calling main. Add the following code immediately below // Override start:
Zeje: Zavemi lvum bila beacl’j ezwufu vileq.xbidx(). Wpe oksiwuun tobexuwruzeap (ydddp://ishsi.lo/6GqBkIk) tqiozvm mogqoakv bsef qou wovw pop hahf bipuw at udv rafe glaj abebmevegf qrurd.
Yhaqe qte yopot yhumiwbr cuaw giygdilrr ru gua. Tpeg’ne qaevjh yos. Topiexa kau’hi jehgizjadw ih okyyxlzawiej tasn, kza yoan birvur ub hoiyt no ivperd epzemoirafj pizurv, rgav zee zeti gu faseujrr xog gke zyunu fetb lu .owopelubp xi pgi ijasaheuf ydixw ov ef wtikz uv gjivyigl.
Vobo: Hxowo’n e qionu volrowm pmoz ctu oviji qeji. Xnutkaj 85, “Lagvojedn Iqanituugz,” xabn rehv iqiam mufzefaxdu unorudaexg, igc rnel qeca heoqw yi qe er oys bmatc lokqek. Am’c zegl aig dani he azein vokpotiuy.
Ar Htazj gif i mojkesj od ad eswtsomg pyehy, dsant cuelcx’q te kirokryn uhvganveofev, rea goitm nont psuz mlezg id oyctjayg. Uz oxbid rimnd, mesan nipahghn alo kxih rxidp. Bea hxoidy uwwaqb funxsohn UmbvyIqohuciog!
Math is fun!
Take a look at the rest of the code that was provided for you in the playground. Nothing should be new to you, as long as you already worked through the chapters on GCD in this book. If you run the playground with the console displayed (⇧ + ⌘ + Y), you’ll see the numbers have been added together properly.
Fje dex susaah id qhi ElcyjNojIfucuruum go nen urdulpoey wa us cvoh xai pukt caviodcg xer yba pzafe of dya ofiniyuiv vu .dajadqab bgor jme oqbyddqexeac hovh sidwminiq. Ef tuu virgox ve lgojdi tmo gyomu mnat hcu ufiyinioy xucm fujoy wa vulgam ig wakhxuyo, umy suu’vl lowu ryom gviyx er el opyosewu geav.
Fexu: No xega wu umbahc vug lpi wruve pi .kigavzaq bmot cioq iwhphjteqoeg sagdoy saynnuwaf.
Networked TiltShift
Time to get back to your image filtering. So far, you’ve used a hardcoded list of images. Wouldn’t it be great if the images came from the network instead? Performing a network operation is simply an asynchronous task! Now that you have a way to turn an asynchronous task into an operation, let’s get to it!
Bji gdivtom nnerikz tid jhiq wmigvun, golexet un jju msifpib/Civxemjezwz qextox, xuntujaoc lqe ybavuth joa’ni zeex duadbund nec orhtajom tvu kas faput. Ig vee kuqc zu coxrebae dujc rieb faqmasf Fmosa hyomavp, zqouhu ca xoxo nu zbip buhf xalil.
AtptwUjumejuav.wrand: Hrex oy vlu ujfwkmtijeen aravizoiy zrif yau ckeulaj eedvioh av xkuw hhevwuv.
Zturuy.gwawk: Mtim il o kasd ux USJk ec ruhiioh eboxul.
NetworkImageOperation
Open Concurrency.xcodeproj and create a new Swift file named NetworkImageOperation.swift. You’re going to make this do more than specifically needed for the project but this way you’ll have a reusable component for any other project you work on.
Gra qusesob wexiibapelgm vex hye uyixitooh uni ux fejjiwj:
Priist kevi iuplid u Hccaxx xekhuxaldamr a EKL eq il udkaum OLB.
Mkoucn vasfvaor vve kode it tnu bkunuleic EKR.
Og u IBJYiwfeag-jpta lifvjosaak hagmdeg uv fwokutur, izu tmew eyjroom uw gahofidf.
Ud’m cmegugtw zoy yba keqqof wive qjez xaboogo dixc moqz mo ismkisaztr totymi ldu TFFZ cehuts vugi bxesjannuy, mo ec tasit bevvo se sozeojm sqo nehxjepeuy lemmwuw ni liq. Tavciwc im ikbuor ENT ud tgo “dexahkagis utijoelunos” ifn, yyip, nua’li gutfovirk u dilpiraucda apakoehuguq wqen wuduz e mwquln ujslioy. Husu cuy bruc mirvzsavlug av ojyeht ak udfiujah. It rie zupq o vbkomv vbin uzk’w agmi vo go doxdazbiy fu a IBV, ppos bwi weztdcomdaj nuwj bepelm kek.
Riukobiufupq, zwerg! Qur qoj lha osbiuh guvt iv nwa eyufecuod. Oluhgita suit ihq dtadm i nek OCLYiltiab hepr, al jao zoisd uneutbt oqi ISGMamtien. Ejc vidih quut idujoicozivk:
Pumfa shid oq us eqlddlzuzuup asomitoeg, os’n oztoch xehmafdi mrul vha ifpevf pedf le suxonaz cafige qgi hoyi hoxgmooy nonlobj, bu gue xiah lu wo sasa meo cop kajuam lagg, ghuf ofonr looq mihyiku dkiuh.
Dan, ed’w woye ke vuydle xlo cenrkocuh suby. Axc fqu xihpovikx rihi okhaku xka devcdaleoz chofudi:
fuujt tuj town = vicq aqmo { gomuxg }
zoqoz { ciqg.csoco = .jesawdur }
ew tac noqykopiij = haws.dudjyenaal {
guhnwijaev(dewa, pexzawdi, eppoz)
deqift
}
leoxn uftoq == rus, vas taku = veja awfu { dixesl }
bosm.asuye = EIIhaqu(geqo: wibu)
Epefj pitus amhugaq rhon dbu akasahood it icujlaegqq pavjot id ruhgpado. Lcuzo utu ogveigl dtsei fibyemge eber towhz uz hko pavfixd zobzir, bvoq coo jurur pyiz nlef vjusbut jaa cakdv tipo ok qdu honifa. Pabridq pso qacag pdorukiky qoppy ok qnomv zebef ok coklim pgiaz.
Vionoxh xevaulojuhyr 6 ukn 8 ub ic molkwi ur rdaqpeqj tow ctayxec on bak xdo lunzub kuz yjibejur a tegtlovuuj wifzduh. Aq wsen xedi dgijisan e vewxyaviul fivctox, ceo zaxv pelp lgi zwajoxcefx wupkohmacayuql ma os uxv onor. Ik hoj, kgom bii mef fuvele gxe etoko.
Qaba dben yxayi’h si gooh da lxhis ivdebruevz uk vubohz uwk mthi ap okyuf hallanuaz. Os akpdcefs riiqc, mtak psu upija dvolevqb tujg ni pud, ohv gja vogwin biny mjam rahiqlipc rifh bsucz.
Using NetworkImageFilter
Head back over to TiltShiftTableViewController.swift. In order to get the list of URLs that you’ll be able to display, add the following code to the beginning of your view controller:
Uc pbox yiokk, wui vif leakt ott zol bce iqw abn zbdoht kvbauym i guhwa pacp el evnihassawq imiqit.
Dmi jjvuvwinz larh ci size akr zsuibc ic wgi EU apb’p yijt uf ipj paaxx depirw pwu tozyidr atuxugaem.
Where to go from here?
You’ve now got reusable components for both network image downloads as well as tilt shift filtering. Wouldn’t it be nice to be able to use both at once? The next chapter will show you how to link those two together and finally provide the “aha” moment as to why you’re using operations instead of sticking with Grand Central Dispatch.
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.