1.2. Decluttering continues...
Now we will look at an example where we will edit a contact. We would need to make two API calls sequentially: delete the contact, and then add a new contact with updated data.
For the sake of simplicity in this tutorial, I will skip most of the code; however, I will discuss the most important parts.
Let's look at the updated delete and add contact API calls:
addANewContact(contact: Contact)
//MARK: add a new contact call: add endpoint...
func addANewContact(contact: Contact) async -> Bool{
if let url = URL(string: APIConfigs.baseURL + "add") {
let response = await AF.request(
url,
method: .post,
parameters: [
"name": contact.name,
"email": contact.email,
"phone": contact.phone
]
)
.serializingData()
.response
let statusCode = response.response?.statusCode
switch response.result {
case .success(let data):
if let uwStatusCode = statusCode {
switch uwStatusCode {
case 200...299:
return true
case 400...499:
return false
default:
return false
}
}
return false
case .failure(_):
return false
}
} else {
return false
}
}deleteContact(name: String)
Both calls were defined as asynchronous calls. Now, let's look into the code snippet where the user taps on the save button from the edit screen:
In the above code:
I am sending a notification from the Edit Screen to the Main Screen to indicate that the user has tapped the Save button. The object in the notification contained a tuple that holds two values: the updated contact and the name from the old contact.
On lines 3 through 12, I am writing a Task{} block which enables sequential async operations.
First, on line 4, I am calling the delete API and waiting for it to complete.
If the deletion is successful, I then call the add API.
When deletion becomes successful, then I call the getall API and refresh the list.
The code looks certainly more readable now!
Please download the whole project and study that to understand the concepts.
Last updated
Was this helpful?