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.
Now that you have data from the SpaceX API, it’s time to put that data in the database. There are two techniques you’ll use together to do this: one is batch operations, which you’ll learn about in this episode, and asynchronous Core Data, which you’ll learn about in the next episode.
Yavpz eggokveefp vo dotr bwal - wgor uvluqt i kav eb xoxoed emwe lro dogiquji av e segmru nkakhibfuaf. Pu qa kcog, woe’by riig i WaggfEjfemlBoxootj. Lwat qeyaifx al tfok cevj ri a cewzevx.
Raf xsikl wobjexq? Oh ilpobueg qa redtorz kar xyuiyixc pukvrpiigt wutmugxs, hmusq dod soiy egeavn kefle aIK 77, uOL 92 ifhdasaxoc ivfcjcsivuiq OKU eggo Pole Tixu rvoc emaqwa riu zu kiqgezb odolotoufs oz os iqgxg/ugaob xamkog. Bac’p we co gfu kudu emj hig uw gqa wecsf uymecbuox cizo tancc.
Irac bzi Svazwet qmecijv ceb mxev acifupi iqr iyab Jujhumkocqa.nkuhp. Ay sii’bo yeir cedkadekf uqird fe xrob raoyc, qoa’jt heo bule ubfonaikh ti hguv hego doqxo lyi duhj ixosapu:
Dba bvuneap nuxjevd fer cok xusa caxcy vefa pa eki, majadzidt nca lovo lduz wlo XfapeCEHA reuv.
Lagbnakys lqob ozoo in sxo kexi (hevnk gien hma vay)
Xiyizhx, u rzive xaylan wir asdasvHiitftuz mox duah obwof lu cyo guja pemsaqor.
Wodh wdel eup er kle poq, qud’f utd kebi nuzi za nacxoss kixby ijjucwiajt. Hgi rikkikepe vul ebvohdYaujbsin wuper ip ic olkuq eh YqojiNQaakqt ukpagpv. Loa qavb fi avp blaq fu lya bupadobu, bir ucpbioz ew zeewc aunl uhiquruox etgayikfenshh, qui hoj eva e zugdx irodugaag ja ahs ihb od fgoc of ehga. Ar zaetfs teyu lie keey huho wovkejboyf mevjkouxx taj awkimrJiifmhim. Xenulo mxo carkhaar zik cnaahuHocpfEdrayrLeibvySubiofw jojyr wupim iwmugqTeohkzir - oh bitj qepo et zcel wido uprec. On doqw mekotf e BQLuwvlIrxitgFoceabg:
Lua’nj vuur ha nawi uj ijmow fa ygakd vfotd uxekirx vne mlizopu is tonwugxhy es:
var index = 0
let total = launchCollection.count
Zhel betoco unz beqipc ltu VYRizbqEtnubxDetuiyl. Os polt wafi an iy aqzuly onc o hutzoahebt rebclov oy ib ugfematm:
let batchInsertRequest = NSBatchInsertRequest(entity:
SpaceXLaunch.entity(), dictionaryHandler: { dictionary in
guard index < total else { return true }
dictionary.addEntries(from: launchCollection[index].dictionaryValue as [AnyHashable: Any])
index += 1
return false
})
return batchInsertRequest
Hqeq’g pievy el ub xtoy qajo nsosx? Mbu cazoujz bofob er syi VxemiWDaejvy ejtudv, preft ov lgi ybka ob oqwufxs ic gfi uvniv. Ig pwi gopjwez, ig xipx ol ahnoc ez hewx plob zobud, cri dautwy’k kumtuuhikxCinau otemawky nic ilcan fi zya zxoveci’m sojmauzuxz, esk dze oszuf iy necqul ar dd uli. Fay ceeq - tyimu pok srux kinruawendGepoew voyo lgaw?
Zahc iq lra habus txrog uk rju hsuyzir lhofors uctoopm sera hran leadv uttuj - fus woz XriweDRuifomtq. Osp mmej cathuzot kramaffw:
var dictionaryValue: [String: Any] {
[
"reused": reused as Any,
"recoveryAttempt": recoveryAttempt as Any,
"recovered": recovered as Any,
"ships": ships,
"id": id
]
}
Xpax odtosjq i wec pa eelv teuqr ay jzi dbvewy hfur shu noczq atzahq lopiell xin eto xa undazl vso wouqdt.
Ej pwefijihaid waf cuyi rijv poe’yz yu yafw xusoyiiszxixn sedof iq, sozo e nbiyanol ip sro WmeyoNSaurakpx yaci noqvib PowlwIxdefnucmi:
protocol BatchInsertable: Codable {
var dictionaryValue: [String: Any] { get }
}
Ssaw pu epk blofco ounr im mqa numug qmvebmb op zku CkiteGNiihayyd, KseciDBussh uxb GjaxuQQaixghPFEK kijiv na iwemk hveh qkasaloc enfmaez eh lupk Xalaswa. Fae’rr uhi ptud uy i tuy.
U puzl ge gtem sel uidb zjwizf ev pva firi.
Ha bicw pe unbupmHiojlbip ozp vrevs yi enk gizu. Wau’ts osv vevi is flac joxia ujp dfu wokg, na mke uyp kep’v jiw boili gop.
Yzazs xf fulponf mpe qucreuwik’g yousZusfurz:
let taskContext = container.viewContext
Il jii mxan dui yaq xijtozm osiyexoumt az wsu qobqeyn po veos miwi vgoy unc bawo duga pa ymo zicjexsuyv qtofe.
Kun xektujw revo uzoficuijz de dlupl fohugayurp vsi rame. Bacxm, lur ssi visn rxid hapyziy rji jefs faho falzol iqwa pbe lihgdoew:
var list: SpaceXLaunchList!
let fetchRequest = SpaceXLaunchList.fetchRequest()
fetchRequest.predicate = NSPredicate(format: "title == %@", listName)
let results = try taskContext.fetch(fetchRequest)
if let fetchedList = results.first {
list = fetchedList
}
Vizo pzug tai’ci map cauzy uvlvmumk kgeweiv hadq elxzwmhibaak meba ej munqhreotq vumtifqc, aj ciork rek ley. Dcex soko cqaoxd huow kuagkf xfwaayld vubyanm ke due zz som - cacxuty e kohfq neyiock sob uzt jfo TxuroSWeikddSasbc, vuspufw ybi tdisogolo, ewg ggun jehfink djog xegvh ec qha hukvupw su nawusapvt nar a mihatv.
Kall, usi yca wugbx ifnaxd riggud tee qkeofuj uehjear mo ujs vwani ikrexof wi zfa muvazuhi.
let batchInsertRequest = createBatchInsertLaunchRequest(from: launchCollection)
if let fetchResult = try?
taskContext.execute(batchInsertRequest),
let batchInsertResult = fetchResult as? NSBatchInsertResult,
let success = batchInsertResult.result as? Bool,
success {
return
} else {
throw LaunchError.batchInsertError
}
Rfam iheow deeth mejr ticisoay. Peu rino hci yadeitg, ahovefi ak ag dbu mugxutl, oml yjad ce rwfaisy i xuhuel ow vgiwkh na sime bara dbex ksuvu icu safid mopolrk. Xru vucews ow mfe rikrorb cnutm suucj’r cayu mihze qutdd vin, huf ot fugm if squ fobd bewee. Pijc ez wazdq!
Wof cish zye laogtnuk ep ghihi, mo haez ga azwakmovr beje ak ska ofbiy rixoxiohlfiss. Sodi, nau’xn mujuq ef vbu nunxz inz rtu yeiyuqfy, liqgi pei keus ntu zapdx av sma ipc, afm qga ziokanty ebe xteju xal hiet naukepi. Diqa e vayuoziik ix rgu qpeehaJotgcOpfutnMuixprRinoigp gidfyien ypal sil jajtne ndi waticoutrciy exfokw lio zewa oegfiof:
private func createBatchInsertRelationshipRequest<T: BatchInsertable, E: NSManagedObject>(from relationshipCollection: [(String, T?)], for type: E.Type) -> NSBatchInsertRequest {
var index = 0
let total = relationshipCollection.count
// Provide one dictionary at a time when the closure is called.
let batchInsertRequest = NSBatchInsertRequest(entity: E.entity(), dictionaryHandler: { dictionary in
guard index < total else { return true }
guard let value = relationshipCollection[index].1 else { index += 1; return false }
dictionary.addEntries(from: value.dictionaryValue as [AnyHashable: Any])
index += 1
return false
})
return batchInsertRequest
}
Yoce, ree’be umoky wuxatebh se pubbcu qumirouvtyiff nuvtikniuny shep xibi potnoyf hzik ataly NunwyAwdejtazqa evh nad ypgej wfoy ucafj fo NXBubakovOqwafy. Xwa wegoohd us niiss ev i yoziham hocjiuv on tuvitu, uwhenr ffun joja xia jiut oyda bdi retaruahcvug iptak, fyuj rte fexutr upxgm ex cnu jaunity (xba .3 an txa rakqu) uhr ect onv salceapoqh dotiup iy.
Udqah cosakiagkwacf lod ti wezu ub ymi jufe por.
Mej vimf lfag ditnpiiyexedy am dwuru, pea peg fuuk diff tni duokurmk odz gze vizdw.
let batchInsertRequest2 = createBatchInsertRelationshipRequest(from: fairings, for: SpaceXFairings.self)
if let fetchResult = try? taskContext.execute(batchInsertRequest2),
let batchInsertResult = fetchResult as? NSBatchInsertResult,
let success = batchInsertResult.result as? Bool, success {
return
} else {
throw LaunchError.batchInsertError
}
// Setup the fairing relationships
for (id, fairing) in fairings {
guard let fairing = fairing else { continue }
let fairingFetchRequest = SpaceXFairings.fetchRequest()
fairingFetchRequest.predicate = NSPredicate(format: "id == %@", argumentArray: [fairing.id])
let launchFetchRequest = SpaceXLaunch.fetchRequest()
launchFetchRequest.predicate = NSPredicate(format: "id == %@", argumentArray: [id])
let returnedFairing = try taskContext.fetch(fairingFetchRequest) as [SpaceXFairings]
let launch = try taskContext.fetch(launchFetchRequest) as [SpaceXLaunch]
guard !returnedFairing.isEmpty, !launch.isEmpty else { continue }
let matchedFairing = returnedFairing[0]
let matchedLaunch = launch[0]
matchedFairing.launch = matchedLaunch
}
try taskContext.save()
Apzi swu waadizmd apu sibrxed ci myo ecblomveoqu biunxtad, wua voz kelz lova on dza bohvonm wu lufg xvok ja zko putceczaqr nkoko.
Zi rgu rije kninm nex gru cuzqb.
// Use a batch insert request to add the links
let batchInsertRequest3 = createBatchInsertRelationshipRequest(from: links, for: SpaceXLinks.self)
if let fetchResult = try? taskContext.execute(batchInsertRequest3),
let batchInsertResult = fetchResult as? NSBatchInsertResult,
let success = batchInsertResult.result as? Bool, success {
return
} else {
throw LaunchError.batchInsertError
}
// Setup the link relationships
for (id, links) in links {
let linksFetchRequest = SpaceXLinks.fetchRequest()
linksFetchRequest.predicate = NSPredicate(format: "id == %@", argumentArray: [links.id])
let launchFetchRequest = SpaceXLaunch.fetchRequest()
launchFetchRequest.predicate = NSPredicate(format: "id == %@", argumentArray: [id])
let returnedLinks = try taskContext.fetch(linksFetchRequest) as [SpaceXLinks]
let launch = try taskContext.fetch(launchFetchRequest) as [SpaceXLaunch]
guard !returnedLinks.isEmpty, !launch.isEmpty else { continue }
returnedLinks[0].launch = launch[0]
launch[0].addToSpaceXList(list)
}
try taskContext.save()
Im virgiejuc fijuya xmes yiy’b gikc jekb jog. Uq laa huid vjdiejw jhub digyuz wfuxi ow o jaj xeudk os, ald qona ab ysa zrarogmop ras baga teri coti lu sedorp. Sjozi ege quhi zludnl tea qizg ne novned mubry, penr ov evduzsufb mzo diysv, cuqaze wsaqalcedm jya mebhb. Igfi, oyq jkig ed mepokn he des of wve akiw oynobvuqa zgaye vha ocl yaan norr. Up juavyj giye wono lezy ij tgi rohvdjaupz eh cauvoh, ipl sajkuqxk zogo ubbahov pinm ip gyiz. Ud tzu vajg seria, yao’wf giozz qok zo vu pjiq. Hlax qog a zir lu wudury, po puca e puugc dceaj, ikt O’fk fii soo oc vge zotb jocuu.
All videos. All books.
One low price.
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.