Я звоню API, используя alamofire и кодируемый. И я получаю ответ API успешно. Но когда я получаю дополнительный параметр в этом API, я получаю сообщение об ошибке типа «Данные не могут быть прочитаны, потому что они не в правильном формате».
Мой код здесь
Мой класс модели:
import Foundation
struct SingleUserProfile: Codable {
let result: [SingleProfileResult]?
let success: Int?
let message: String?
enum CodingKeys: String, CodingKey {
case result = "Result"
case success = "Success"
case message = "Message"
}
}
struct SingleProfileResult: Codable {
let userID: Int?
let firstName: String?
let location: String?
let state, about: String?
let totalScore: Int?
let sun, rising, moon: String?
let ego, communication, birthStar, sexual: Int?
let intellectual, temperament, emotional, healthGenetic: Int?
let profilePic: String?
let numberOfPhotos: Int?
let imagelist: [UserImagelist]?
let verified: Int?
let dateOfBirth, timeOfBirth: String?
let age, isLastPage: Int?
enum CodingKeys: String, CodingKey {
case userID = "User_Id"
case firstName = "First_Name"
case location = "Location"
case state = "State"
case about = "About"
case totalScore = "TotalScore"
case sun
case rising = "Rising"
case moon = "Moon"
case ego = "Ego"
case communication = "Communication"
case birthStar = "Birth_star"
case sexual = "Sexual"
case intellectual = "Intellectual"
case temperament = "Temperament"
case emotional = "Emotional"
case healthGenetic = "Health_Genetic"
case profilePic = "Profile_Pic"
case numberOfPhotos = "NumberOfPhotos"
case imagelist, verified
case dateOfBirth = "DateOfBirth"
case timeOfBirth = "TimeOfBirth"
case age = "Age"
case isLastPage = "IsLastPage"
}
}
struct UserImagelist: Codable {
let userID: Int?
let imagePath, photoID: String?
enum CodingKeys: String, CodingKey {
case userID = "User_Id"
case imagePath = "Image_path"
case photoID = "Photo_Id"
}
var getFullURL : String{
return BASE_URL + (imagePath ?? "")
}
}
В моем постоянном классе
let SINGLE_USER_PROFILE_DETAILS = URL_BASE + GET_USER_PROFILELIST
typealias singleUserProfileDetailsCompletion = (SingleUserProfile?) -> Void
В моем Api Request class
//MARK:- Get profile details for
func getSingleUseProfileDetails(currentUserId: Int, accessToken: String, completion: @escaping singleUserProfileDetailsCompletion) {
guard let url = URL(string: "\(SINGLE_USER_PROFILE_DETAILS)?UserID=\(currentUserId)") else{return}
var urlRequest = URLRequest(url: url)
urlRequest.httpMethod = HTTPMethod.get.rawValue
urlRequest.addValue(accessToken, forHTTPHeaderField: "Authorization")
Alamofire.request(urlRequest).responseJSON { (response) in
if let error = response.result.error {
debugPrint(error)
completion(nil)
return
}
guard let data = response.data else { return completion(nil)}
Common.sharedInstance().printURLRequestParameter(url: url, urlRequest: urlRequest, accessToken: accessToken)
Common.sharedInstance().printRequestOutput(data: data)
let jsonDecoder = JSONDecoder()
do {
let person = try jsonDecoder.decode(SingleUserProfile.self, from: data)
completion(person)
} catch {
debugPrint(error)
completion(nil)
}
}
}
Код работает нормально. Но если приходит новый дополнительный параметр, я получаю сообщение об ошибке типа «Данные не могут быть прочитаны, потому что они не в правильном формате». Как написать класс модели, чтобы при поступлении новых данных он автоматически обрабатывал ситуацию
Пожалуйста, помогите мне решить проблему.