11.5. App11: Add a new Contact
The code is unchanged here since we just upload the data and do not necessarily need to parse JSON responses (for now).
So let's put the code from App10 to addANewContact(contact: Contact) and onButtonAddTapped() methods:
//MARK: add a new contact call: add endpoint...
func addANewContact(contact: Contact){
if let url = URL(string: APIConfigs.baseURL+"add"){
AF.request(url, method:.post, parameters:
[
//MARK: we can unwrap them here since we made sure they are not null above...
"name": contact.name,
"email": contact.email,
"phone": contact.phone
])
.responseString(completionHandler: { response in
//MARK: retrieving the status code...
let status = response.response?.statusCode
switch response.result{
case .success(let data):
//MARK: there was no network error...
//MARK: status code is Optional, so unwrapping it...
if let uwStatusCode = status{
switch uwStatusCode{
case 200...299:
//MARK: the request was valid 200-level...
self.getAllContacts()
self.clearAddViewFields()
break
case 400...499:
//MARK: the request was not valid 400-level...
print(data)
break
default:
//MARK: probably a 500-level error...
print(data)
break
}
}
break
case .failure(let error):
//MARK: there was a network error...
print(error)
break
}
})
}else{
//alert that the URL is invalid...
}
}Now, let's run the app.

Previous11.4. 'Must Do's While Decoding JSON adopting CodableNext11.6. Adding Accessory Button to Table View (Edit/Delete a Contact)
Last updated
Was this helpful?