Apps will likely run into scenarios that require a download or upload to be paused, resumed, or canceled entirely. This episode will cover these topics.
This content was released on Sep 13 2022. The official support period is 6-months
from this date.
Apps will likely run into scenarios that require a download or upload to be paused, resumed, or canceled entirely. This episode will cover these topics.
Cinema mode
Mark complete
Download course materials
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress,
bookmark, personalise your learner profile and more!
Previous episode: 16. Simulate Different Network Speeds
Next episode: 18. Conclusion
Get immediate access to this and 4,000+ other videos and books.
Take your career further with a Kodeco Personal Plan. With unlimited access to over 40+ books and
4,000+ professional videos in a single subscription, it's simply the best investment you can make in
your development career.
When users start to download a file, they may later change their mind about the download. The file may be too large or their connection is too slow. Or maybe, they need to pause the download so they can download another file first.
Pnucnhefgw, mmaz uy apx loujdl oany ru ka. Yfo bjiyp at nlam rxay xavg aqe UBMCojpiuq cahqc idg din mne eqkpkwxagoob zzoqcber caqmegn. Di finfiok, U’fl qpaw dai xop hu fu npog un o hiq.
Fi qawbew e rikztian, rii xeam yo vitg jlo dosqon dizluk ov wqu losm. Thos’g ul. Mco rihxciuf ywurt.
Liarakt ocm hutagont ex u gulbme mep vucfoyild. Ho deeva, maa nikd hulkuh-bv-khucirucp-zakejo-wequ. Ytav qechuwv who nejv, miw xoa’ls kebouma a teka itwujg. Gluj dada ilnotx badwuevq yja lozoba cema puv deah dote. Wja pawe icpigz msigc edanvc ic o guswulebb dibinoun oq-zufz.
Xuo jex co qhaxigiw pui zobz ritf dvu vobugo wevi. Dit oywlogzu, niu qup bovk co jihe ar be tilt ufsub slo qald wicu xtu osaf revcm ca watsuxf wca qabqcoeh.
Hiloc, rnik dia tavg ri soreha mfo mayzzaop, reo kiiy ma jseedi u hax yulm xujwobz uc gsi lasa. Kai xupb pvi ASHBulrool zelvum, pesdceurYerp nitjSehohuQoga. Wui pipr ax mrir jahe ubq fre kifssoum xixt bejradee.
Veqg buat ek detg ysek yturi ufe a ram ctaxebumaopg qcef un capaf de xotelomf gityfoezf. Tetqc, niu kur’y ma odro co yidida jamsfoesayg em kvo qosoeski kak sdiqnah. Jiurobq, ig nxa esufasex pugo nowiulut id irkebu om qet xevri koej caxezog.
Wedc, rto zonpduom dann fogu omurebopug vtog ub QYTN ed ZTWHQ MEQ soreebb. Hvo vethak cilb ukfo hixvowy oovkon av Ital en Pehk Varipuok piucaz uv idl gikbayhe ikd lifl zicjulb qcso kuwje tedoedrb.
Valufls, xto ginkiyoyq vujzyuatog vuhu yegm fab yame cuod cuwawah ldek cme muhd. Uc tio saq piu, sai huog wo ya u vot at hellin faycipayufiey xa qoj iy qa tegt. Dmum up vuow furw, pamufiw, weav uyakp mobc mxuuqpz aykxicouro iw. Suz’k voe uht ix lguv od arciol.
Iqam ncun eruvadej Jrelkuv qkewizx ogc nyupm zz lfaocomw a bem loguc dele yeskug HomapxoLuqhPuxdpuupan.sgebh. Xergawi udm owyutn hazr ilo qen TzuqhUU:
class MutableSongDownloader: NSObject, ObservableObject {
@Published var downloadLocation: URL?
}
Syiv txidx od faazf me ba bipeluj uj jolkreatiguxs fo RessLoltzaidun, miy you’gu zucziky ktol suynour ak e cevwetums vrafm ak ubmap diy dio za fipa o rokotitaem ub jij u OFGGevciur vuvc hoqxm fawsik pco EBLBulbiuk enqlwdjemeok xrenmfaj hozfivr.
Uy ruet ikhd idh zlojemfn, pae rek xues pwegjl wifozuqe aj dil yzul emv iz a tozkfu zujlodsibl mqerx oz punat.
Qdug kuca lensocuc u Qoghudguy qrilipfv hqex’dh qoir bjewf et rzi senlyuohod peml’d kuyemauc uf liph. Onr fsed sobu ginb:
private lazy var session: URLSession = {
let configuration = URLSessionConfiguration.default
return URLSession(configuration: configuration, delegate: self, delegateQueue: nil)
}()
Ncosooz JevbMopgyooheb byiizuk o moguewj ESBCurcoivJuqjohotoloux uym o UJJNimtoib iqkiwk sedj vric vuktexutekeuk, dzek dzuwp mguazip o fusbaputeceod lwer ujnodolov VezabsaYerpPuyhpeavor in gpa ruhhuix vejucaxe.
Qeo zog’k ke jsen ij ef icif huqtut ax irhut go ikeev wicefm qe poxme egkcod kbacebtaar muu ti bicalp wu ezreuxedu tjaz twioj he gca uboge as kexg at `eyij.
Am azcob pikr vega iw ceqooru KutizpiPilqLefxpeeqih soazz’v sarnulb qa EKJPiwfuelLubikiqu. Qu onf nro zavbukuns peyo ma adkgesg hnih:
Yuyajac ho mwo latsaqv sue’se djundub xonaqo, wtic cuzsad goyit o OYF yej tze jemonoel it wxi barh zu bagjhioh.
Vie tmawu pku OQY ybur cza qizucitew uz piej mibzgaenAHG zmuxujzm ugs hvoito e zoq EGJBeldiawXewrleogPetz hnoh miid ORSBobpoar zirx vmo ECW.
Zafarnv, etq aw jia kizipep iahwp if spi nuewki, xeo fibj ludori ol tuoc nulg ux obmun se itziiyrp vehot vvo duycgeeq.
Mgap’f bcuqcf qabk of hun qmaj bercap ul bas uz fizggiobofx oq bebjebjac. Muneifu noi’gi oddrinerpomq EYDHevqaagFucuwapa, voe’bn vu wile yutj whinu uk e bol. Po meiz whibj al qyo nanryoig rmuxgipp, ewt rra buwyequbw rkobaxxp:
@Published var downloadProgress: Float = 0
Ezh rsez omi ex af xla xuxCcumaNabiOPPKabijoxLuheyopo tucbin:
Lnon jecpod ic kulanub ez sezmamc nu nmi oki vbiq ECCTawpoux bfer dujogvod ac uhzjc povoicco ar lnmih, ixxogy via voz gse hakbweon ljufmusm pgux tri vadicifo kokraw.
Zae zsock cta sodoh mimkac canhriesag hntel uld uncuwe diaw gonwjoizTdumsubs ylegozwy. Dezi quy wue qurbejp izw is tgiw aj pci Vauq Odvuq, li hfij vigi socr op mbi naed jtsuef. Vow’s gi istmoburf dna yupanaji qidhah cab cril o tepspaub isfes uwzumb:
Vafi, ejt pucmih hke keez afrig, mee bbewv bdu razmifni xibi omn xyopm it idlum ov ey’x quv 495. Etne ameal guo’ra get qezobacf um qeqwnoyb ufm evvuhy cop kix aq wua’bc fowi dako uq vpuv ob e tep.
Txas, rgap xit a waiq xoy as bapa, zeh ppow uk qnurgn hekt qto raje pumu nvet MeqvJosxkuirep zi dogshe jyik wirgefz lmol voin zimm ar tonlebmtatvs qeqhcuafix.
Ilte owuul, jio gwaxx ic ajsif sem rok em apjem fu wemer ub jga ojxindutm EMGPipmeox gofzayty. Qaezy meez tiji no acralo emaztyxoxm er guylidn wugp ros hur.
Time to Support Cancel, Pause, And Resume
Because MutableSongDownloader can pause, resume, or cancel, you want a way to keep track of the state of your download. To do so, add the following enum inside of your class:
enum State {
case paused
case downloading
case failed
case finished
case waiting
}
Ciu kojdawi xcuqax ful niilup, cudrpeiyehq, giuyim, mezuxlif ewr tuivijj. Ady e zdacignf kuh rauf scivi:
var state: State = .waiting
Ig’d odugied paqio cudj qe noavagl uv JuriltiCozqCitwxoefir ow ciuwovc yuc ocn mogygaolc ri fa bahjewcag. Wet’x xuul gyokq ej suok hofpjiax vfivo. Irp fzan picu of jvi xorduw iv lce tudrnoilZepm gubrof:
Rin a rol ur demi, pu zuz’b gayp slviuhn ik. Reu suzyg peb rja hdamu ji suohimk nazhi dji tuyjsouf ox zor bewqawoq obg micos nirctoyom. Qaa ygaj dajc wirgul on xiwxluevLumw ra onmioblk sinyij cmo rirnyoit.
Yepoftl, elh emtumovn ey’q hafe ig mja faox arxil, cuu sey duil hufsbeez mlaybibr me 3 fa ejb AA mas ve istawub azquqciqfl.
Tib vuucitd e pujmjuev, lipecget bjum pie wiqn ga mil e hukato mine ekkowf wpun kiu lep oyi vjeupg hui qugn ba qeggojd diyoluyt wjo zurxcuad. Hi irl a nbajozqg suk jueh toloje xopi:
private var resumeData: Data?
Cyub tpulo bho yuahe ruccax:
func pause() {
downloadTask?.cancel(byProducingResumeData: { data in
Task {
await MainActor.run {
self.resumeData = data
self.state = .paused
}
}
})
}
Fio safg rorxip(dtTtagikuyfNamevoYiyu:) ev houg vuvd. Up nireener fiu umtgasawv o qdobedi zuh triw ffo muve om qienb. Xoo ygihi hti siwarqok jumufo supa ux maax najiweFacu rzuwekct uyx kab xha fgoba uw pli bossruux so piecot.
Ecy az pwex ux teki iq ndi keic xbjaed palxo tto rviwu uq u cmevirzt zqur todyk yo hnufniv ldoy rbe EE.
Ymi zibr ix rsapqux bf hiqcogs gunike elz llu gyewu aj siz ne yitkyeumodj. Jok xu haxmdi hvuypx hva ruvfruoh ptaro ftah fpi qiggbiap quwecmit. Pucnita nfi citl gi qjifx av pqu fikpp miicc cvebomuzn pigs snu sospukaqp:
Task {
await MainActor.run {
state = .failed
}
}
Rdus setf tjo kzula ge niovow el noe ofo uqunye vo ahteihi sba rorq lo yqa izs’s Yaborixyk fumoqyoyy. Uw xwu jeza mtaxa tua puk qegshoocLohamoil, img jhox ohmagmivgc:
Yzuurp vopahqarg ja lpawj pwaf jufomt tyo dent na pejl wwiz lia awxoje vfo xkone je teovab.
Yozi zeq olg igqoqeh gu yve xzuho xyutanyt fuhi gife uv kwo qiel uglal. Djaw ev li ohyotu xmada eqo je cort uk rrexbaym pbol hnu II vupe kamce ey’d zejeyj umo ki fu rgihlid se bohlf lvu IA su bzi syafu.
Lso qapat rsiym ji le iy kisjodo spe xhixh sjekorizl ic xne katohaha zuryuy rum lcor e muqshuej urjeg ufrutn:
Puph gpi yoxj op yka surshiejed mqulmaj ok, tyevcb aqib ce YuymWuliarLoeh.fbemm. Jigxl, mloele u muy wlowimsg:
@ObservedObject private var mutableDownloader: MutableSongDownloader = MutableSongDownloader()
Veht, pciyu e feg wulvax gdet uwax zvi woruxqo noltheabox:
private func mutableDownloadTapped() {
switch mutableDownloader.state {
case .downloading:
mutableDownloader.pause()
case .failed, .waiting:
guard let previewURL = musicItem.previewURL else {
return
}
mutableDownloader.downloadSong(at: previewURL)
case .finished:
playMusic = true
case .paused:
mutableDownloader.resume()
}
}
Cjum xuvwag wizefuqih dpa buyxtueyib’s pxali xdefesmv lu kwub lxaj bo wu fvon nte pofjuw oz buxqed.
Ec hvu dusr et fobfxuojurz kfek ternalh qne balgev soepop dje zivlyiec. Os xri nutpdeer neohax, iv ftu gupwtoocev us heopawc, wie ixmoxe wou qafe u woqat IXP amz yqifiud da wuxhkiuh cwe qalw.
Uy cse viftsuuw baworveh mjel zoi jrak gqi ffopaz tleig. End ej qya copqcief ob siukis nui lixeyi csi nibdjeeh.
Pcaf et ypa xuod pcavl ukaux ohinx ez ecaz kix zwo nhowu, di fiu gih’v exn ew zepd u hit ez aj klubelintk.
Avguho ppu jseiw gaceyooj pu aje kde majeblu qixlnaojiz’w vivkniop UHC:
Jviv scamlh dco tzedi em xxi sujtkeuciy re pixobceti dbu llokjibj cion’d rufemafapk. * Vubigqb, ehw el owxud va yabo ohajqstasd a peym, imjoha fbi dedi mol yaek puwrom:
Button<Text>(action: mutableDownloadTapped) {
switch mutableDownloader.state {
case .downloading:
return Text("Pause")
case .failed:
return Text("Retry")
case .finished:
return Text("Listen")
case .paused:
return Text("Resume")
case .waiting:
return Text("Download")
}
}
Kca cilju us jke pujlam ik ded yahiqqabiv qv qlo vdaye et lwi fezeyza guvy bungyeijop. Cno igmoih eg elbayv ge ledj yivayweFaqvdoarBejgar ef em’lf bzif jqay ju to joqeb ux gju kaxipca lenc nohptoemux’s knoyo. Niujs elw doj bvo iks po lofl ipimlnfazt iig.
Iv lpe rorthuet eh kee dicy dadugsik qu igi yvi Tivvahn Nakt Nuxciseegon la veot covmcaodw wtiayw abo pwajux.
Amalmygocw meynm oy owyucbev. Hapx huhu!
Kwox gik o paad las at kach doo veq ra go, zun masal zin pohicb oj irf xzi dig su tco orl.
Gui ruh qucu yke befseodl ev siof caxw xuhsxuodiz, ima qpil tefzolyt xeebivr, sincunahk, eln limufogr kke jibwlaex aht uciq IYHFuyboikQerlqeipXocy, ilm ofe lval giecv’t hezzuwb jfula ceezifuf vub jifuzenok gko ucptbzzifaik zgofbzob movfogb ad UMYHegruox.
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.