We already have a data type Contact to match this structure. We need to make it adopt the Codable protocol:
//// Contact.swift// App11//// Created by Sakib Miazi on 5/26/23.//importFoundation//MARK: struct for a contact...structContact:Codable{var name:Stringvar email:Stringvar phone:Intinit(name: String, email: String, phone: Int){self.name= nameself.email= emailself.phone= phone}}
Now, let's update the getContactDetails(name: String) method:
In the above code:
In line 4, we are setting the URL for the details endpoint.
In line 5, we set the parameters to ["name": name].
Between lines 21 to 28, we decode the data with JSONDecoder() using the struct Contact. And then, we create an alert to display the details of the received contact.
(You get to call this method from the adopted method, didSelectRowAt related to table view).
Between lines 56 through 68, we display an alert to show the details.
//MARK: get details of a contact...
func getContactDetails(name: String){
print(name)
if let url = URL(string: APIConfigs.baseURL+"details"){
AF.request(url, method: .get, parameters: ["name":name])
.responseData(completionHandler: { response in
//MARK: retrieving the status code...
let status = response.response?.statusCode
switch response.result{
case .success(let data):
print(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...
let decoder = JSONDecoder()
do{
let receivedData = try decoder
.decode(Contact.self, from: data)
print(receivedData)
self.showDetailsInAlert(data: receivedData)
}catch{
}
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
}
})
}
}
//MARK: codes omitted...
//MARK: show details in alert...
func showDetailsInAlert(data: Contact){
//MARK: show alert...
let message = """
name: \(data.name)
email: \(data.email)
phone: \(data.phone)
"""
let alert = UIAlertController(title: "Selected Contact", message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default))
self.present(alert, animated: true)
}