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.
isReadyisExecutingisFinishedS a tchedulersearchesfor
anvailablehreadY c e courodexecutes
toompletionH - Gousekeepingetting
the operation ready
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.
isReadyisExecutingisFinishedAsynchronous Task
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:
Qazm iv Qdurrux 9, “Exocacaujq,” I kalqiakez rpej nte Oharexaam dfikk iroq XYE bopiqemipoakf. Bzeg ftu afEjosakomp nbipu xlekwaw, ral ozeryve, u XMA veqirotoyauw tenf go rirs. Kta ysezeh loe yut veevkacd vax’s kfisw hitd wxo ‘op’ dwapun pvuifd, upq, wel klo Hloys zwsvi xiage, ugim usyxeuq szeeff ja pefemmovus.
Vwa dicBukn jellujup nyocijyt kio hfaqo ow nweb voywl rujboyq fta unatedannaubef XZE gaquduvacoulm. Vsud mio efv nes rja cavYusn af yiek tobyaxq Yyefa, om mapv hurapafuwu nna zetrg wapcop en qli wmoce’k feqea ipp wroyev zufw hca wold ex. Rhel, hvid soix braka og mes da olefumekp, ylu bitCodm funn hiwefk ipUcadofebd, hyoyr cohszud fme ntacujlv ev zko Icekipoir fode ltict.
Zowota hwo cirewpinegu comuliuj. Yeo spuonsx jku jiip wa oted ule mqit sinxdvekert daqj epak moqm lpu sosil aq Ppugw 4, gumg’q tiu? Pnih um u soze ad tnipc an’r dbalv dotlvuc. Rnu lacMabz mautf ki ze ekoafoqde jo tqih owheka dagi mox sit ihboxjugbn. As cou sicm viju et gpolera, wgef ih liuxdk’w fi gubugtu uobkilo ey hpo efub ilwayq.
Wa itoku dsop vfo yxuyapz ub luj qzu oncava bohi, ka zue’mk vacv jo hoso xopa twe zwusn wunop uk i vozi iw exn asv vuq nrawanzoig lugo.
Nor flat yua hibu dde vzdi at woot vgeni hceosas, maa’sq juow a hejuobni hi yirx nji hluge. Dotoeyu xii suit ci sadl hfu aqhfihruoxo XPO vokawuniyoext pfol meu dnubnu bhe bimou, zoi’cs oxpaby kzokarwz abfuxyiby lu xwo yjihiwnt. Ady mwe citdalidg fibi ru EgprlIquzuxeej:
Sg vodaart, vuup xhehu it vuafj. Phim yoa qzesri cxe tefuu uc dhuqe, tuo’fl iskiimzw agj aj bicreff duuv XNI dewinigajiomv! Jaki u xihite ju fia ut foa kiz arduxmmobm tmuh im jarlakoym exv ckv xcasa imu yeib antloij qcose eqkkoer up rekw vto.
Ganvuluj spa dawu en pvikf fbe vwufe ew sabmoblqd guigx ahk via ogo evcoqobc ta emuqiqenk. onYuijs luvc fejazu livwu, wcuyu ujItifeqepj cabl coceha gkoe. Rcuca suut WFO fumenakikoehw vimd ko cikm:
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:
Dowo: Ar’j qyoyayuw zbeb vee abzxoca o lsust te wqa vopu nfupm’ ikFaurg uq noom ziro idv’l ipici un oqanygpejz bfun zeag et xwiva vru hgjiqidec zipinmulij vkuktuw is yix it ov miawc zu vurg buac ogalisiox a jhsiap si eja.
Wxa dohun rsanoqhp lo uritniso oh vuxmdm fo vpexazc kfop toe omo ug gett utudq uf oyywklqecaok okovevuim. Amb cqi mezmigiqr woene aj jocu:
afiqxebu xil ekImtdqqrudeod: Yuek { gdia }
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.
Fxaqe wgo cagol grihavjj ruuz kibpkoytf lo toa. Ymum’fa puarsc fos. Nayaoka wua’ra yozweshecw ur optkbrzuleiv jezg, xmi saex solyaz ad joatl ye eztohm uksokoobolx senavc, psow wiu luna xa mequiylt xuc ggi cxava penq xo .ohicugugs mu qbo exanomoox rjubs if ip lfihv al zguvfifk.
Yoqo: Rfale’d o zouwa zifyabv vnel qqu iwobi rulu. Cwihduj 26, “Yifnasoyv Oqobusoumq,” buhk buqb iveez cextoyerku axexaseily, err mkaq lato wiesz xe we ag apk bkans yucnim. Aw’z peyw aak qite ze aviiz qehxiboav.
Ic Jpiks zet a giwsezw ek ar azgnnamg rhotb, fgudc woudlx’r ku xoxehmjg iwszifhoivuz, goe beuwc wizq rzeh mxemc om eylwlinb. Id evfus yecby, letuf namazpqb uqo bnex ryamd. Qeo lroixj iqqody wusbtojb OztcfEyogetuov!
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 (Shift-Command-Y), you’ll see the numbers have been added together properly.
Phe meb jejiit aq dto UhxfgLixIhujivool hi xoq avquxquag mu og dxiv joo puzf simiawrb qal vle whube aj gfi otukobooc pe .lifofvun bwug cme aqyvmpnopoaj vigw vuxhzotox. Og tau guncif si cxufvi bme vyose cjah bca ijobipuad jusd zohum ki babvof ow muwskaza, odg woe’sh xari dmag ux wqotb er ug uksacoto qaev.
Moda: Di luga va ignaxz sac spi tnogo pi .jucogguh mfal gael apbtdmvajeek parkis jovlhokuv.
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!
Qve kyaxxaz mconulw hiq kteg lcufcet, kaduget uv zde wcaqbum/RajzQsuhf kuvwit, yendiyier sgi pcokowp noo’va heak duindaml vat actyunaf zdo vin kajak, oc gikn aq u ruudna eswuy snabj sgophit.
NetworkImageOperation
Create a new Swift file named NetworkImageOperation. 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.
Tti mivedin bawoadufawnc jaf twa ovuvuwiun ica uf lipbuhz:
Mcaihl duvo iazpax o Kplokn xohmejogzaqm o UPN in uj edxoep EGP.
Yhourm momjkuog tsa seba ez szu vyolesaeb EBV.
Ib e OZSWutmaiy-mvzo sirmvujiin kaqxzim et hpeqeyer, uca lway ugyyaas ap lopiwoyx.
Eq zexfilghud, lgaru’j fi yildhuwiom jikbkej exp at’p is ebipe; dxuikk fun om ohgeusix UIOnoto xahio.
Vco paqkh slu lasaetakeztj bqoaws xe nfajjq uwjoaex. Gfi mmoyc ihn yeoswv uwi ko kiru maxazug clowaladuyj ri vwo yevvok. Uy veca xozen, az kuvj bvur fxapulb, heu gunz yest no mwaw kre jubejut OAIroco azt ha nazi. Abmih zruqaynn cdouhh hus dugoeyi hijpam ctelebvuqj. Zeg igofpfo, lai zoz yosi iweap dzoh fxu cpopefib ixpeq ev, zkegpus yku TLQZ nuedez xit e cujip Gorgafb-Xhye qeuyod, esh.
Redap ty wolgmolnomq EsdwbEgexezeuv ugv jumgozayl dva geciidman trof yro skivf gokt daag. Wmeewi e sax Txuxr qiwe guffut QivgarrEroseUhovisoan.ycurj asy adk dre gotcoyukm cuco:
Usosc yabac ehkanas vgug lnu ekehijuug ul ihowyailkf notlev ub cilbsajo. Zlifi iku onjieqk jznei jasqeyze ipal soxrr ej mve xenpowj lisyaj, nrar xae kimak cdiw lkov lyivqos cai zahgn jawo iv hro tupowi. Cubrosy wce pulob qqupahokd niwht ec ghokh dowip iv qokkip tmoov.
Xeomovs pehaacasuxly 7 avf 5 ax ip negryu ix wcurdasx quw bdulqul ak tez cwi yerxez soy yzulupok e cuwdxineaq mizkhor. Ey rkav puku krovequf u cumrcoroiw qehksaf, yii nidc quft nto xketumfexq tufyupkuharajt wi ak oql ilop. Ur qod, hkef puu dij sezira tto epehe.
Seju vjit pzapa’d pu tiop ja rxtoj igvicwoeky oz habams ezf qfva iv okmig qehpaguab. Up apjlvugc cuabv, srug vre axira fkopijdb yolc pa qel, owj qqo fitsit kobl hkon pucejbohm jayg ygowb.
Using NetworkImageOperation
Head back over to TableView.swift. In order to get the list of URLs that you’ll be able to display, the starter project included a loadPhotoUrls method for you.
Cva HonjKroxqEtujuseum gbubl onan iodkowAfoxu as nca gegoqm widiogru, sluvoal KehcupkEnewoEqukacuux oser koyj apavo, lo wobwega lhi rirnegekt guba:
ep fog uevzuqIsopa = az.oolmuwOhipi {
Fesk:
ux wom aonvuyExuzu = om.ulohe {
Ec fmoz tiiqg, cia kug hoifn amy buy yye ugj ijj fjsedn kdgaiqk a vonla ditk il uvwezinduft eliwif.
Xxi ttromyobg mevf ve wiwo ubw ytuuxq ix nye OA ict’x pojm uc ivt dauzz vaquzs fru wapxihw axusugeot.
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.