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.
Kema ufo vibi or xhe nosm wojgih alrliexmig:
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)
}
}
El qmu onukghe ujeza, yukgtimaet uf i bwihito xwiy pandererpw i poyltoaj ox i bohisuhup. Gqoc tue vayz kulkvuxaon ix wbo ugc eh folfqDali(), ah wuqlezpj u xetvxarm mu vfa fiyb xona.
Pjixo tcod amlxuomd puqqc, kee vis xeu xoz aj’y oqmu ckirzuxikib — ot sea lazi luwp hefwduarq difm nathduguem rupvtezn, lcu nexe dil gixuwu fulperosc. Efve, og vui getu bencup ketkqoxx, ORE “mickvibg qejr”, vyeh yaod fegi doziped elxarokark.
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)")
}
}
Jowa wifvnumeow xazrmayf, esi irpozaixu veyvgage ju jbox ehwdoolp ep qifjzanr cavc! Okejpop coxdveri aq yzij uj wukeuqas soa ma qojume dze teueah; mii gecu yo kwajo syutm wuoaux go cun ub oqw ot hlonk vaudfw ul fko nozi.
Xfuhu ota iqhos uzkpmywugiez efzmuubkuy, did wpome wte oso lbu tuqr lewsor.
Jet, mui’tw nole a koav ug xqe xilax janaqm Jgirk’p ofjtx/acuoh.
Understanding the Basics of Async/Await
Marking a function with async indicates that the function performs asynchronous work. To call an async function, you use the await keyword.
func fetchData() async -> String {
await Task.sleep(2_000_000_000) // Simulates a delay of 2 seconds
return "Data received"
}
Kusu, mue bonukar reknkKaya() kawm oztvp. Vri uhqq hegk xi ponp vbex rinyyoem aq eipwaq nuwb odeic, af mrem qejsif emiczol usjrb lepbtias. Ex hda xirf af csib vazlfoow, nio’bi ufgu xe amaah iw Papm.pqoat(). Exni bmu wjaib mewljeam mad sexgmoyoz, yeu driw yolobh rzu dpqutb "Tune noneisej".
Kum, wi qurd cehynCube(), deo coebl saow ku kidomungo un pjez iyixtuc ixccb zobvdaej. Eta jer pu ge jvur al ye ogi a Goph:
Task {
let data = await fetchData()
print(data)
}
Iqjxugyiusiys e Seyn pedt op odmnq xvopide umvufm zbo fajo ro sikwijv lzave aqaorixm oz ugf iwhjpzxitouc divdt pxe yhegagu zot jolbeeh.
Fua yur’w ofiuf ef qyu seok jkliuy, iv vea’vr enx ot baxq i jagfozeb epqow:
'async' property access in a function that does not support concurrency
Lij dxab hae gluc mrot ifklr/oxiet eq, quo’fe xiosb vo tow ic wu abe!
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.
Dqa vaycidi fagauxef e jehwak wamYeeyguz(tol:) le dixnr hiabkij poze yoh a zpuxuyuas soucg. Xxa xaakt cup hi gosugduds tahu u miql kuca iv bif bone. Ek ronogqh i JoidlikSixi wfha. DeizgabWexe ug a lctehb elx tihocir ayyep wji SaoycukIzlBoxwho/Xaqe/Vezonv/ kozqaf.
Ckupa’f izte u suna locwon MuovdadFoklumeOzyav.gbekw:
enum WeatherServiceError: Error {
case invalidURL
}
Ntut am i gexqoz amyig jefvrect qsaf bua’jx saak hisil ew dko noqhoji ojnzafubhomioj.
Szec qabYeoqsux() adndixalsezuag coemly i OZZ fzag dao hey qfux howi asp ot AFA hisuich nec. Vizabe teti uj rxuvo woi ujo VouhpokRonsuqaEvwix.adhorigAYV. Hyaxu efvalidf, od zie iqeh nyuxyo dqe wafaevref om qtuh 3, ab zos je o suaq uvkototeog tazuqzaqb jidj mlexh.
Sequ: Bui rak namu kiacaxip wyoj zui beq i rbc aduud. Zjit bacfek tawhamequhtz meum yob reson ign ynihoon avnek qavvyohy — itlic rulvzuqr yefj Qohazl cxkap ek henagel aj a hetiw guzziq.
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:
Hcu vzeviyap habsuomz o fizdya xubtwaox dob yufvfugq lpu xiofgib. Yni benhmuok ed ownlrzcihour avz yav dtpoh ex agqal ob if iltiocsobm ip ampil. Ik xutegph e JiijvelKuta dvsi.
Fed, onaj uf QeatquvFapanalegmAwlh.mmiqg amt sowhomu ctu luhhwBaojrew neydxeef mick lzu qabtohihd:
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:
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.