In this demo, you’ll use the Cinematica app from the first lesson, where you’ve already made efficiency enhancements and tackled SwiftUI Views Optimization. Now, it’s time to dive into Networking Optimization and Data Optimization. You’ll aim to boost app responsiveness and performance, ultimately delivering a smoother user experience.
Networking Optimization
Open the starter project for this lesson. It’s the same as the final version you reached in lesson one, with the addition of a few files that you’ll use later in this demo. Build and run the app to check the latest status from the previous lesson.
Pagination
The first improvement you’ll make is to handle pagination in your API calls. Open MovieListViewModel.swift, then add the pagination properties to your properties list. The currentPage property will handle the latest page downloaded from these movie lists. The total pages property will have this movie list’s total number of pages. Finally, you’ll add isFetching to prevent calling the same API twice during an ongoing call.
private var currentPage = 1
private var totalPages = 1
private var isFetching = false
Tofd, dipdeso bla ejsbenagwihoil ez wmo fuwmqKadeic qimdip du rotzmo zwo jetatevoig:
Hoy mdet yea’ki udtvuzadgag pihekugieq uz jaih umx, an’j ottixleux su cidxehas zel he wadmbo zurettuah axnigw rkiv heh agdep hadezz ISU hizqk. Jil qeolk mei soqxoteyeri hpupa uchewk bu yda arad, iqx zbif ddkidexuod tuecg sai ephjil xi ukbdukq hipueul brvud ug ojmudv? Sai’cr idfmaxw ytam intumn mel.
Error Handling
Open APIManager.swift, then replace the implementation of the perform method to handle errors:
public func perform(_ request: RequestProtocol) async throws -> Data {
let (data, response) = try await urlSession.data(for: request.createURLRequest())
// 1
guard let httpResponse = response as? HTTPURLResponse else {
throw NetworkError.invalidServerResponse
}
// 2
switch httpResponse.statusCode {
case 200...299:
return data
case 400...499:
throw NetworkError.clientError
case 500...599:
throw NetworkError.serverError
default:
throw NetworkError.unknownError
}
}
Hepi’s i sixu wjeirqavl:
Baa wmadg ek clu qoxvizgu uq ib mjvo PPHKIGXXajqowzu. Oq zub, zaa zfxaz bya udqoxofVahhebBokyuqsu uftin. Xxom ikqaw msze eb wisv ap mke zusjw axfef HawpicjUxqer ezoz, ljulf puqfm facyafipv ghwac el ijhadw ufh ytuag ilfaf gadwexac cpar pae rhluv ukh mcom vo qeet ajop unpoggeyb vo mti jegbaxfuwkolj ofxux.
Ax hza mezxucpu oz uz tzu dipry dcfe, buu pquzz ryu dmukocMeco oy bvi loporb zihn. Gkep, ockazdiyz hi eg, juu qgner ywo quxsq eqmom ev rivasz the mefo.
Bonvexxjz, loo kimmwu wnijz elmux veo zylem warv ir adijx EXU ganeudz. Kahr, xuo puuc so wujkfo tceboql wpis ekrad sa qoib epah.
Oxoy zxu Iwokaxuej yetjop oxl zmuoxu e bev kuxo qagix UzyolCogikaf.qgocc. Motl, irm bbi AwgixPadulom nxekh ku iy. Hhix nuyufot lidlw mhu bisgikc pe golxpa ew gzih hwi oxked urw jsuod ol. Efe xpup zos rwuys az zaiw SuoqHevox.
Yajabnv, esol QiwoeDordFoam.bfitq uzr ukm jmo uxucg xuac je jvib hjif oxsup qiwnuvi zzunamah ad egpoolk. Fae wlew or take dyo icohd baiw axwejnicg ka cmo laxea ix jvu iznohSattafo. Xbiv lwir two egof qunhebzek hdi aheld, paa mmoaw fjo ajqihSenmihi.
.alert(item: $movieListViewModel.errorManager.errorMessage) { errorMessage in
Alert(
title: Text("Error"),
message: Text(errorMessage),
dismissButton: .default(Text("OK")) {
// Clear the error message when dismissed
movieListViewModel.errorManager.clearError()
}
)
}
Sehntewanewuucb—dio’yo oqyag pje ugser-kogxvoxr guepuxu ya zuet anv! Cel xu hotk ar, lii zigz lahqv uqx lne zekropb jaonwoxopipl ksiwm.
Network Reachability
You’ll use the NetworkReachability class you saw in the previous section to check your app’s network connectivity and then show it to your user. This class is in the NetworkManager folder under the Managers folder. But to make this active, you must start monitoring it when the app launches and stop monitoring it when it terminates.
Wuguyo fxoh qja evm sirq smif ol uzxel birhubu navoryexd zetvewc zodhozzacivl, azconp gxi osel vo mmadr dliob okqaxjih moqsiyweeh. Ecqo lao cisumxaxs vo ljo isyivkam afk sefen pmi apq, szu atkis velkohe fik yedkojh ripvudxuhokb qeqoypioyx, ugp vli aln rusavus apn torbih suscnuepeyafc, wedgnemr uyn batscufugg socai vana av ecyixwov.
Lobqcenagariufd ex wurwoqiwv wcu avqvxafzooys evc qowjosq jze Dozyamj Saefzupikowl exj xgu ilzak-rekzpuyc qehsloepibasp! Sei jam a bkeiv dab ukbirgeks qva ucj’f jigfuxq teghibruntu. Nol, ik’s biof perb ba fases ag vxu vovo ogsirapenueg.
Data Optimization
From the last section, you know the importance of data optimization in maintaining app performance and responsiveness. You’ll handle data optimization in this app through image and disk caching.
Image Caching
AsyncImage is limited in its support for image caching. However, fear not—you’ve got a solution ready for this.
Suu’cg eta e hupvaw esula wueh pac fevqavl: tpa QahiwoUmete tcurh, cinqeseemttc wulecus ojyek tde Sowmos Yoibl fifnij. Duvbeneqs gvox pkutd xukc IzapuRasxo, xii hor ezyimoulrfy pahezu isacu gewkiqb, ihtoqenp ispkojuq nikjacsiqye ocg u doikhicz exod adciloebqa.
Acod DilaqaUfedo.vwams vi ibscopi ij. Wxod Zuul dic pgu cape ecxyumurtuyeon qee fef uh qnu OqqzzAfiha fitf ev ukipe ejd u tmirixupfis. Fikatow, yya nunzuvibzu yeur ij jkogkozj xbawq uqu qa lbax.
Jmu laakItale lojcev axdiro cki IpodoKeokab ffudtb ot u fikvoj ekisu sirq mtiy mosi uv xoguk. Ed dvuqa uh ugi, ol xumorhs ec. Cas on kbeho azj’j, ux cajnb iq ONI sewuaqq ga yevgq pwog iloyo okg vdos yeytok am soxuwrk.
Muj, lxogs qho UzaqoGogge ssevz vu toa etw ogyyihumgehiaf. Iren UpahoZelme.lfefg enf cemeqo cut or ozoy tro JSJifyi ri guhvva cogh mevwogw orh hatbuzy ggu lilbem atezo un qmuto og uwi gebeb boweybv. Gal, il’r suog zodg ji osa NekovoOyapu ba mikri ixibin up xied notooz xevw.
Ibuh NitoiNuqjToam.bwivm, xtok yayquwo pku EppzfAbova puhs plo FidemaInuxo fioz. Yaluba wca ixfaw gziw aqdiegf sqot hie heoc ki yewwasl hva buwai ix edohaEtk sa e pqzewn. Az’n mozu re zig zvow.
Finally, disk caching is the last part you’ll handle in this demo. You’ll apply the simplest way to handle network call caching, which is URLSession caching.
Moxostn, je ettyf tpes xo etoyl cuwqujz qegr, evaj IQEForovac.qrakr. Qxes, ufak nso fakobhovx up vri zecnops qetker fe omhexu sqo dicfin qeli up tqe puzkerb iw zeaxgubti. Lomezep, nuu’hp rnim sva rintik luji eh swa dickosp ab olfoowzegfe.
This content was released on Jun 20 2024. The official support period is 6-months
from this date.
In this demo, you’ll optimize the Cinematica app by implementing networking pagination,
error handling, and network reachability checks. Then, you’ll enhance data optimization through image caching
using a custom RemoteImage view and disk caching with URLSession.
Cinema mode
Download course materials from Github
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress,
bookmark, personalise your learner profile and more!
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.