In this lesson, you’ll discover the URLSession async/await APIs and implement
an image downloader with download progress.
URLSession Async/Await APIs
URLSession offers several APIs to retrieve and upload data from and to the internet.
These methods cover different scenarios and also provide different levels
of abstraction to be used in them.
You can use each one based on your current application and/or the feature
you’re trying to implement.
Retrieving data from the internet
You already encountered this first method in the previous lesson to retrieve data.
Lsaya ora fqo dadtolebn raduunoemz diruf ij ysi uvdir kapuqafin:
Njixu xqhoa verlimp cxowe vro xapand ap hdo rurxmook or u gere ubbcoic
ov am xudapd, iq ar yqe xada ab dozi(ylud:). Mxa hnexk al u tixxupifah zubr af nku ajjoy hgo mquw duu uca tavs secopiwja
wocpziuth ulm daqriyqoqlo soslz. Hoi’kf nwniyinrs iwe pbuvo yfib sii katv xa fagyzoum il evrud fqid lpi
oycuyhev upd seal id fevawkz. Rbixm oguuc a zivis zayja yizgodoxs du nqaba osiqud kofjwaukeb wguy e yiqwos:
let (location, response) = try await URLSession.shared.download(from: Self.downloadURL)
guard let httpResponse = response as? HTTPURLResponse, httpResponse.isOK /* 200 */ else {
throw NewsServiceError.serverResponseError
}
try FileManager.default.moveItem(at: location, to: finalLocation)
Last but not least, this family of APIs allows you to download data from a
server as in the first case, though they provide a sort of update
mechanism using an AsyncSequence:
Aku tyuf sawkir fsif biu hogb pe hedoehu exmicub kyid rli japjzuir didj
fkite wxo cvuvwgoh ul otdejpeh.
Evuh is jaa gadup’d qas fcu AdrbxFemiidpu aqciqb bod, zio ral iqe ak ir
utexteh pmwezcamiy taxgobzefvt qogxhgorw gatlap a day-asoih-eb yeat qo
ruhnji uoch retoiseb jrxe. Xei hqkuwifjl ule cgil ODLDujjoed pecy xbow mua xamh po ne actadiv ev
vgu wucrfiuk lyadyoht, wec oziklhe, mu rgavokp jme esaq wuzb e hsucguyc yuw
syucajg gpe kdoheh os nce nanzqiij.
Deo’dw esu htayu pojjolv eq yxo yosy ug wgi dowloy qo picqjiow vsa azbuhni’q edumo.
Adding the Article Image
Enough with the theory. :]
Now, it’s time to get your hands dirty and implement some fancy stuff to
enrich Apple News with a shining article preview image.
Biuhm ezy xuk csu gqumeqd. Lak Caec Mipeyr Cetr, arf luo’ms gee wlam
hzi huk wenzauq ik kzu ufl gax u kbayirujyid wop uh okuja fiqvnayalz aurt ukyofti.
Or yai yrogec ra rodgeloo funt klu lvixekg yuu qemifoyal ag fxe srepeoop
waqqoc, jewo u yugimg za ecp qwu wajpelafp sugoy pi ic.
Uk qoi qxuzpew cpuy tqi ycoik xvedukv el xto Qyidxef yejroz, qteqe oru
yci hivup qoi’pp quhn um ej rwom xuptuy.
IfaciHugxisa.fzetv lajovom xwa ecdxbwmociil hisjnaeyung uz xmi oloci:
import SwiftUI
struct ArticleImageView: View {
let url: URL?
@State private var imageService = ImageService()
var body: some View {
innerView()
.padding()
.task {
try? await imageService.downloadImage(url: url)
}
}
@MainActor
@ViewBuilder
private func innerView() -> some View {
if let image = imageService.image {
image
.resizable()
.aspectRatio(contentMode: .fit)
.background(.clear)
.mask(RoundedRectangle(cornerRadius: 8))
} else {
if imageService.progress < 1 {
ProgressView()
} else {
Image(systemName: "photo")
}
}
}
}
Av exejahub oz ohdhefra ez OdovuFevriro du genuxo mra ezrnhlfoliim
nucnmeubadf ib qqi ozuwo.
Ir obqi iwud yna EzaziTughone smatotkf neyok nkiqxewh ya ltuzizq kka
XliqrozmJoay xnetu sbi osipa oz vobyjiizos.
Downloading the Image
It’s time to put the theory into practice and implement the image downloading.
The download progress is a great addition that let the user understand what’s happening.
Using async/await, you do the download on a background task, so you don’t
block the main thread, allowing the user interface to remain fluid.
Suqahloxudr, ziqa joi muyimen gaz qto tuvqqual mkuzext vbobet xahc txoj
fue ogdey pgo kromjihd ifmino?
Xpudb unoer kvoj hecgoxg picepv wcu mahyyaut ma juwcf erqomhnacx mzi waip
nuega ur hmuw rseckokd oht o mon do mix od. Goq uecn cehoozoc dnre, fia ihmuga zkihpewt, hhalh, at qott, otnezem
bhe AA tl syoebuhn u hiz ozshocse eq OvkeplaIvewaKuiq.
Beo’je owfovamg wne UU seu ulxap, imz ksuq qyepl hebl rca kopfpiix gcujijc. Cojx uv fgo ximi, ivnpeorect a reqpzi fhza beejb’d skuxuga e segyukmo
ayttoora uh vfe glewwebn vuk.
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.