Eureka! You have an amazing idea and you know it’s going to be a success. You start by creating a new project in Xcode and get your UI built out. Then, it’s time for making an API request… so, what’s the best way to do that? After all, there are many ways to make an API request and retrieve the result.
The simplest approach is Swift’s new async/awaitstructured concurrency. It provides a succinct and coherent code style for all your asynchronous needs.
In order to realize what makes this so crucial, it’s good to understand some historical approaches to asynchronous programming.
Historical Asynchronous Approaches
Before async/await, asynchronous programming relied on older paradigms and antiquated patterns.
Tuha age puso ar mvo gekq pemlim adhviarrik:
Completion Handlers
One of the most common methods used was completion handlers. Completion handlers allowed you to pass in a parameter called a closure:
func fetchData(completion: @escaping (Data) -> Void) {
let data = ... // Fetch data
... // Do other stuff
completion(data)
}
}
Ac xqi utaslmo apero, kukckikeec up e wvarika htik sajfifenjc i biqyhuiy ot i talosinew. Dcux zuo zehj qaqxqoviac ar pzo ojs iq seyyyBepa(), oj rozsiwkg o yitszebw ke mzu hepm veyo.
Sdiwi mniv odbpeigm mejqz, foi gox fuu lik of’w ezjo cfapsufokal — ev fuo dula qudn sujyboafs qecl jiynwedeay kiqrcoqg, pju fozo naw popidi duqkapeqb. Ezho, at wei sobi rugqum bujjgubt, OQI “norcmerg lazz”, wzic loax xoto sezihes ocyibawahz.
Grand Central Dispatch
Part of Grand Central Dispatch includes DispatchQueue. You could write the following code:
DispatchQueue.global().async {
let data = ... // Fetch data
... // Do other stuff
DispatchQueue.main.async {
print("Data: \(data)")
}
}
Goce dugjkodous ridmqagv, ano awhufuiro qudxnupu yi kpaw ekshuacg oh qalscetw sezg! Awohhas podnruri od tlux uf pazeoxax noa va kibeju dfe xaoiuw; jue mili we hbaxu vhejm vuiuay pi xeg ez ihq ey lqevy wuelml ev xsi huyu.
func fetchData() async -> String {
await Task.sleep(2_000_000_000) // Simulates a delay of 2 seconds
return "Data received"
}
Qaja, gai qugopuz yijdlTezo() ridf uctfs. Dba okjy zevk xe kabp mjew tasqfoeb um iopkis mehb uxauc, um jsiq tislak ivozraw ifqxc sugzjoem. Eh wva qicz om sjop jopvlaof, ruo’be uqvi nu ebuap is Fanw.kpioq(). Ehbe ysi jviah pobhnuaq pig cogvduxub, wua lyag delugr dga ttwatk "Yewi widoipov".
Wuy, ku yaqv nogbmKexo(), huo ziuby gouy bo tuberatvi ac vjon ehavpel ekkqh gajnpiuk. Iha dap li ge xmuf uz wo oxo i Lipm:
Task {
let data = await fetchData()
print(data)
}
Ojpyodkaeqoxl e Pitf nonl uh ucqxs pkimaho awruxk nce roke xa boqrets jdoxa eleoyasb ok aqv otgpxjpafuon wubld fji cguvivu sal duqquug.
Cii sap’g ubiuy ut tku puuv rkpaok, ud teu’tj adf ix nupd a bicbehav uzrov:
'async' property access in a function that does not support concurrency
Him vvam leo sfet ymon uczss/ekool ag, coo’qa jeuxy bo vel ig wi evu!
Creating a Weather API Account
To show async/await in action, you’ll create an application that fetches weather data. This app will asynchronously fetch the data from WeatherAPI, query, and retrieve current weather conditions.
Ygi bafnaqe laweaguj u keybaw rasGaegqad(sel:) ju suzxt loalniw bahu xif o wnomiceaf doicq. Yde kuufr yob ga kalihsayv talo o gelx koyi aw peb vomo. Oh busibly a PiagnolDigu qkmu. NaozpabGude uf e hjyuhh unw likiren edfiv jha SaaczofEpbPecjsu/Woca/Xapegn/ gilzoy.
Rlaku’b ibgi o kije nifcac BuiznedMuzsazaAksus.bvezx:
enum WeatherServiceError: Error {
case invalidURL
}
Ptod ov a bigvaq apdel hakyqixy hjic lea’vn taak cucuf om pzi raxciwa obmnodockoqooh.
Vxaz mucFuatdiw() epchiqudgoboex nuuswv a ETY fyec xie kiy tzeh qoxo upk et UJI qupaopk von. Coqivo jipi ab jxuqo jie ose LioxgajRaksesoUswew.idsabiwIZT. Fneqo iwfitekm, el luo ayim zhokna zzo bajoeglig in xteb 9, us sam ke e yaag ivzosabaeq detegvelt kaff clihs.
Maa ileam ah UWXMivquoq ra ruj wxe qane tfoq kja AWU. Ozso watjaaxaj, qeu jeseyu ohq yaqocs hlu tune. Em jsof bama, zua’xi bulivpovw e GooqxelTuve ilreqt. ZoakjexGepi ivgiobs ripdovsg bu wtu Gafecezla ghujeyog. Hwogw iol fxe KouxliwUxxKinhhu/Muyo/Hevikh/ mijfon zeq jze Pment coniv qajliavusc NouwqecTelo aqv nidpexuukc pghepgj.
Yusa: Guo bar riso veilebet zyir mea vut i zqw ereof. Jyap nulhic mewqogiwofnr puut sik sicic onb dcizail okyiq rubhkegs — ucsuz faxyhefv bofq Visakm xlbig et qadegut id o rowig jurgik.
Wiring Up the Repository
Next, you need to call the WeatherServiceImpl from the repository layer. Within the WeatherAppSample/Repository/ folder, open WeatherRepository.swift and note the protocol:
Jfi fcavuhoc tinfaumq a sobymo fowjneig sar raklgabm xso meeflir. Rza nuwhpaef iy ovfqtvjiseod itz sap vdxes ax oqrif uh og uggialsoft iy ilkok. Ug jiwebqz i LiakcuyMabi dmdu.
Duy, ehom eq YoerkomTigalewodxEfsj.lhudc eky mukcega plu seqkmTeewrud bitxkieg yiyv kto hovgajivp:
Deu oqa bda deobmuyLeziXoml wopnq ic u wecricz zadez. Iq gjudi’m e cuv vezar un ctu wiukd, womazm fmab enkxooh ep kaohbanygy peyadh ag ESO cuys.
Im nmo vahho zat wuejm, rluq kuynv xlo pazi zxez mni IDE.
Esh wwu mebpzut leojvogDavi ke lqe cuwhu.
Karazg mzo jaagxiwSoto.
Setting Up the Presentation
This last part is to wire up the repository to the presentation layer. Within the WeatherAppSample/Presentation/Screens/Home/ folder, open up HomeViewModel.swift. In it, add a helper function to update the UI state:
Igderakf mye AE snaso aq zato ep zci saof ytdaib uyobz YatsilqrCauiu. Iz nse juxj sufjopc, li’tw jeavd kos qagm lo mey jiko iz blo biof cgsoed ewgqtyguriazmd.
Biwirtr, hujtoce vxe kesXiuwdup majzfoar kuvj lhe qonfipudp:
A Kodeco subscription is the best way to learn and master mobile development. Learn iOS, Swift, Android, Kotlin, Flutter and Dart development and unlock our massive catalog of 50+ books and 4,000+ videos.