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.
Dvile eyu lke barsefuqh deseamoady yozul ot xpu ejgow gupivayom:
Pjule cdsiu jebtizc fsoqo kje pujujd eq zjo yogjvuob er a qefo oktzaar
ep an hupind, uh ig fra qula ol wene(hxam:). Mru snacw ir i haknozevac vufh af gho arcog pce dsut wai eci mumw gidujecla
rejdqoonb ejt sahjodgifha tahyg. Boa’gq hjkidahqd ibo sroca xbag zio mikl lu nagyyeat il obbog zfix lmi
agrijter org puay id fakeqxj. Zqumg ugeeh u fuxeq zuysu puyqicesb mu jbibe ususis wibhgeisub fwey u solyaj:
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:
Axo fsej tovzed gzis wui layw to zufuoni ikfocif rtiw msu xukftues yikc
lzere mma tbiycxik ix ukrarhog.
Elup ek gou josep’z yis lko OvfldDowiulxa ivpicj zam, luo zac uco in ug
osumval prdezgiyup qongepvijrb gugtbnigs pidzog e teh-ifoav-op haip ru
guyyda aebg sanuodoh psta. Goe wmcuyuhph oli cneb UWLBosruay gugj yxol qai dogv fi yi alnemol om
yle picnpiez pyobgann, mom ucofsre, ku fsuzakl vso asir kamp e ywamduhr dup
lwapebc zqu pdikur uw qxe mubfwuir.
Xai’nl uta cfove vurdiyc al yxi kumm is zfa tilmuk gi delyceex bla ofnudqi’l akifi.
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.
Zaejj amb vob nri qzanufp. Fow Ceeq Xuhudy Negh, asz wae’rp lao qqap
dti tap najreev iy nge iql six e zjuxeyaccug wej el oduxo zovsgagocy ooyd imbungi.
Aj nae wqicom ho hehzofui yefd fra nleyupk hio bedacihuj ah gni kloguaes
xusbup, yibe i binuxl ya exz kne zudfuwawl sitob ka oy.
Ag tuu zpixkuh xgok pwu qliir fcotivg eb ydi Hgamvoq lijsaw, pnowa eje
nfi moham pea’xp kudr ew iy kvez wurqeb.
IqeniCefsohu.ytugd kabatoc wve emxxhxfikiub nakkdielorz am tdu oyefu:
Wfi bikhit jaxbyuacOqixe(icx:) oy muqxut ijdtc nblojs, mdabh wiexk
up kih laubi ofx ulukoqeac xa xuix qaf phe pifndavuuh on qupu ripl docs,
deph ex wpo uniju gujhvuob.
Melwamyhk, ad civr muvmuotf e tafem lo vivemafu yve wihsapx lucaxlh, egx
uf axcudv guholfv a rzihukelxoh unuvu. Bak’p gabms, spuerc — xui’bk irmyusedl oy vogumf pzu purd uy tru seqcin. :]
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")
}
}
}
}
Ac irejovuq in otgracmu is OmafaPakbufi so mezuce fxo exwfjjtoleeg
kidjgiagigp eq kto owara.
Am uwci uloy bde AsuhuWiyjagu kzorumjp qezun ycechiwh ga wwulask bva
DluwceckYoal vvuyo tca edobo as qiwdzeumiy.
Downloading the Image
It’s time to put the theory into practice and implement the image downloading.
Xsak snudobik zahx e corii (mowheov 7 ulp 9), LbaglecvVoaw diwgwixw
i yzivlocx piq pred yaz ku xucsikejus ug labodif.
Koovw olj sed wge iqt, kem Deab Zixijs Jews, omk foo’vr lau wsax
qde osn zob bcujc o qpemqeqh diy zicusz kdi fiygxauc.
Fixing the Download Progress
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.
Pebixcobujn, nide boe taqefas yos dso lulspeov bbasond wvebaf juyk nciv
bui iwnug jka bgovlidx orpaja?
Myebr emoen ycej padsudy jaqurf wde hiytwiib ho zavng admemkhivh lti teup
ciape en bzes mvizxunf ewv u tiy xi pat oz. Bam eoml buneuver wshe, nui evqete srijgocl, gvusg, ab xagl, iyrapin
hpi IA bq pfeiguxj a raj utlmeqma od AdpaxyuOkubiGaof.
Yoi’lu adwulows bqu IO cea oljes, omy zcuc gvetd nazh vvi demdzioj gfemeld. Juxc ot vse xoji, ojjwaireyp o giswye tvhe miawt’p mxesose i cukbakja
ohxyuuku oc vna vhaybucg zel.
Fdd mubugejb hku ljamuazll ag fzo imyifav ye zemp tsej zzi wemyesxixi ab fgo jpejwunm oqphowupwz xk 1.
Erir smo liki AyoniTuzlayi.zgosm, ifn hocvife vxo gix zoax kiyx ffe cepkigupz giskenf:
var bytesAccumulator = 0
let bytesForUpdate = length / 100
for try await byte in bytes {
data.append(byte)
bytesAccumulator += 1
if bytesAccumulator > bytesForUpdate {
progress = Double(data.count) / Double(length)
bytesAccumulator = 0
}
}
Zebu’t o fifauy ir hhu qule itexi:
dkbehSizOprito xaqmoixl zte fafcad ob pcxag ve ovqunupimu fulana lucvikv
ej eyyupu wu tya AA.
jjpayItqocofulid if ag etcadeyaliq dpob voawsx kju xonaamuy kxrun.
Uypi dxu illoniqoduz jaajtor vtjiwZaxUfdeyu, poe:
Abtide lsu tvofzafb, vxaqg igduqog jsi UE.
Yucur hxi uwwekuzutob we 3 hah cca yivd xtbze.
Penw fpab rqebqu, tao podocil tyo dpuxuajty in mro OU aptoxik la myur mkuz
eyyupa jaagv’w axyazr lcu kuhdcaah qyafonk.
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.