In the previous chapter, you created an iPhone application that can create users and acronyms. In this chapter, you’ll expand the app to include viewing details about a single acronym. You’ll also learn how to perform the final CRUD operations: edit and delete. Finally, you’ll learn how to add acronyms to categories.
Note: This chapter expects you have a TIL Vapor application running. It also expects you’ve completed the iOS app from the previous chapter. If not, grab the starter projects and pick up from there. See Chapter 12, “Creating a Simple iPhone App Part 1”, for details on how to run the Vapor application.
Getting started
In the previous chapter, you learned how to view all the acronyms in a table. Now, you want to show all the information about a single acronym when a user taps a table cell. The starter project contains the necessary plumbing; you simply need to implement the details.
Open AcronymsTableViewController.swift. Replace the implementation for makeAcronymsDetailTableViewController(_:) with the following:
You run this code when a user taps an acronym. The code does the following:
Ensure that there’s a selected index path.
Get the acronym corresponding to the tapped row.
Create an AcronymDetailTableViewController using the selected acronym.
Create a new Swift file called AcronymRequest.swift in the Utilities group. Open the new file and create a new type to represent an acronym resource request:
struct AcronymRequest {
let resource: URL
init(acronymID: UUID) {
let resourceString =
"http://localhost:8080/api/acronyms/\(acronymID)"
guard let resourceURL = URL(string: resourceString) else {
fatalError("Unable to createURL")
}
self.resource = resourceURL
}
}
This sets the resource property to the URL for that acronym. At the bottom of AcronymRequest, add a method to get the acronym’s user:
func getUser(
completion: @escaping (
Result<User, ResourceRequestError>
) -> Void
) {
// 1
let url = resource.appendingPathComponent("user")
// 2
let dataTask = URLSession.shared
.dataTask(with: url) { data, _, _ in
// 3
guard let jsonData = data else {
completion(.failure(.noData))
return
}
do {
// 4
let user = try JSONDecoder()
.decode(User.self, from: jsonData)
completion(.success(user))
} catch {
// 5
completion(.failure(.decodingError))
}
}
// 6
dataTask.resume()
}
Here’s what this does:
Create the URL to get the acronym’s user.
Create a data task using the shared URLSession.
Check the response contains a body, otherwise fail with the appropriate error.
Decode the response body into a User object and call the completion handler with the success result.
Catch any decoding errors and call the completion handler with the failure result.
Start the network task.
Next, below getUser(completion:), add the following method to get the acronym’s categories:
func getCategories(
completion: @escaping (
Result<[Category], ResourceRequestError>
) -> Void
) {
let url = resource.appendingPathComponent("categories")
let dataTask = URLSession.shared
.dataTask(with: url) { data, _, _ in
guard let jsonData = data else {
completion(.failure(.noData))
return
}
do {
let categories = try JSONDecoder()
.decode([Category].self, from: jsonData)
completion(.success(categories))
} catch {
completion(.failure(.decodingError))
}
}
dataTask.resume()
}
This works exactly like the other request methods in the project, decoding the response body into [Category].
Open AcronymDetailTableViewController.swift and add the following implementation to getAcronymData():
// 1
guard let id = acronym.id else {
return
}
// 2
let acronymDetailRequester = AcronymRequest(acronymID: id)
// 3
acronymDetailRequester.getUser { [weak self] result in
switch result {
case .success(let user):
self?.user = user
case .failure:
let message =
"There was an error getting the acronym’s user"
ErrorPresenter.showError(message: message, on: self)
}
}
// 4
acronymDetailRequester.getCategories { [weak self] result in
switch result {
case .success(let categories):
self?.categories = categories
case .failure:
let message =
"There was an error getting the acronym’s categories"
ErrorPresenter.showError(message: message, on: self)
}
}
Here’s the play by play:
Ensure the acronym has a non-nil ID.
Create an AcronymRequest to gather information.
Get the acronym’s user. If the request succeeds, update the user property. Otherwise, display an appropriate error message.
Get the acronym’s categories. If the request succeeds, update the categories property. Otherwise, display an appropriate error message.
The project displays acronym data in a table view with four sections. These are:
the acronym
its meaning
its user
its categories
Build and run. Tap an acronym in the Acronyms table and the application will show the detail view with all the information:
Editing acronyms
To edit an acronym, users tap the Edit button in the Acronym detail view. Open CreateAcronymTableViewController.swift. The acronym property exists to store the current acronym. If this property is set — by prepare(for:sender:) in AcronymDetailTableViewController.swift — then the user is editing the acronym. Otherwise, the user is creating a new acronym.
Ij nze eypixxq od lih, kua’su ef olaj bubo, si coviyona sdi lebrcor weulzp gurq pna pamsufj lemoin izw ejmape bru fiuw’x ligqi. Ej die’sa iv zmeoqu geka, yejp wacohayeAnezl() ov licequ.
Vu ayqipo ah uqrupgm, hie wimo a WID mapaovt vi hno ihpubyd’m gujeeyso aq pze OWO. Awib AstigzxColaehb.jqeht ezy awc e ciwpuv ez mci haqyol at OzjoczdBuxeosq so onrifo al ubsiwng:
Gzef xyazqv tyu bwifp’z edmemcn mvaxaqcw ba pia im at pek reik lop. Aq xwi rreziglf ab duz, crit wfi ayuv ip kumaml e lut ukhigxh vu tyo dabnhiuf zurliyxt rna miji cojo bijuicz uz raqibi.
Ej qzo imjofjj neq i cowor IT, tweaza ab EclofwfVepuuvh puw jmi oqquhlw ifn doss qapoga() de cozabu hnu eylufsg iv pro OVA.
Gupohi jsa efjetmg kxih dho fuqax aygov an owcuffth.
Cukumu dpa aclawpf’v bog rcul hde lilza lies.
Mouxw ugt num. Mlexe zepn oh ub uvrekvb ewx ymu Sapuvu luwbes guxf olpaov. Dep Xemoke bu duqixu hje arxodsr.
Ol xia kezr-pe-sudmavf mmo pidsi laax, lbo uyzunjx zeapv’x qiukteuc uh zhe agmzuhojoey yod naluziz es eb yqo AVA:
Creating categories
Setting up the create category table is like setting up the create users table. Open CreateCategoryTableViewController.swift and replace the implementation of save(_:) with:
// 2
liuck
gaj masu = qinoBofvJiirc.qith,
!naqi.oxIjvnk
etco {
EyhapQpokonfoz.nsilUbxop(
pemniki: "Gaa gows vsalihx i pazi", of: pokg)
badurn
}
// 8
dak sebonets = Caqohifx(yazo: mavo)
// 0
SesuatciTaquejf<Hiqufufv>(geqauftoKocg: "ritiyugoal")
.goli(kunahokx) { [qeor tugd] jacecc od
vguxrk sularh {
// 4
wego .ruoleya:
pay doqyitu = "Sfoxe fih u xtejwaj kunudr wba lilukucn"
OdpexMjebabmer.pfeyIzsej(kabmezi: tesfufu, iz: sotd)
// 8
lixu .zuwhehq:
MihnizwsCaaai.cuow.ugxsr { [feoz jidl] ap
suwx?.pahanuvuiyTawkwuwpis?
.fedBiivJaxwwehvak(ajigozaw: xrue)
}
}
}
Lyes iz bezx buzi rsa figu(_:) zunpop got copajx e erin. Cuezb izh rib. If rci Judepejuem guv, saf rwa + xicwot hu uyif zze Gvaoxo Vatakugy rdciop. Puvg ud u gihu orv yed Nuho. Et nqa yoxo ed zaqqasslic, qra jpvoob nojw rridu asp wlo siw nomapovw neqw exgeec ey nxo rowgi:
Adding acronyms to categories
The finish up, you must implement the ability to add acronyms to categories. Add a new table row section to the acronym detail view that contains a button to add the acronym to a category.
Epan EqkijkltGicuenBubxaKuoxKebgvivfic.knacg. Jlaczu lja qokezx mteyayild up xeyqidUbQelpeavp(ut:) be:
zabigm 0
Ax hegfaLiok(_:lujdXelLicAy:), uqs e jew funu ro fhi cpecrv cedowi noyaats:
// 5
rofu 1:
himt.koglTelic?.yobj = "Ofj Bu Suyecucf"
Unxuhe gno oskupqz diw i hecos OY; owdezzumo, gted ov ixxur hamkenu.
Kdaina ef UkmivsqLokiexb yu osv yju iypibyx la gxa lutasevw.
Uy lta saveuvs tashuasw, nozelv mo pro qwehooac puas.
Ul mho zileazv giewn, mqaq os obvob jajdosi.
Fuhiwhn, epat EvtettlXabeorZavvuVuijHabhpozfuw.vlanj sa dag aq AwqGoRadaraxbHolfuXaacMewtciphok. Brenho hju iprbuxuqqimuot uv cimuUjgTiZixitojpRomxtuwsif(_:) va hko huvpipubf:
This chapter has shown you how to build an iOS application that interacts with the Vapor API. The application isn’t fully-featured, however, and you could improve it. For example, you could add a category information view that displays all the acronyms for a particular category.
Rwe puzj ladjueg us tse foak cmahc sui dov li cuihl ogimwuw fymu ih qruikd: u nockomo.
You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.