This is my response in postman plz notice the structure of params here for success response
code:
and also tried like this as well let params: [String: Any] = favoriteMenu
then got error
Error of https://api.net/App/UpdateFavoriteMenus: responseSerializationFailed(reason: Alamofire.AFError.ResponseSerializationFailureReason.decodingFailed(error: Swift.DecodingError.typeMismatch(Swift.String, Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: “status”, intValue: nil)], debugDescription: “Expected to decode String but found number instead.”, underlyingError: nil))))
Response: {
“status” : 400,
“errors” : {
“$” : [
“The JSON value could not be converted to System.Collections.Generic.List`1[ttt._0_API.Models.FavoriteMenu]. Path: $ | LineNumber: 0 | BytePositionInLine: 1.”
],
“favoriteMenus” : [
“The favoriteMenus field is required.”
]
},
“title” : “One or more validation errors occurred.”,
“traceId” : “00-1c8218ae2c3229dc5e2c39448af00e86-0d284168a4488fda-00”,
“type” : “https://tools.ietf.org/html/rfc7231#section-6.5.1”
}
Status Code: 400
so tried to add like this i have tried to add parameters like this let params: [[String: Any]] = [favoriteMenu]
still got error.. where am i wrong how to get success response like above postman
this is the model
struct CommonModel: Codable {
var status: String?
var message: String?
var errorCode: Int?
enum CodingKeys: String, CodingKey {
case status = "status"
case message = "message"
case errorCode = "errorCode"
}
}
@MainActor class FavMenuViewModel: ObservableObject {
func updateFavItem(fvtID: Int, slNo: Int, menuID: Int, chMenuID: Int, sbChMenuID: Int, title: String, urlF: String, icon: String, isSelected: Bool, isModified: Bool, _ completion: @escaping StatusCompletion) {
let url = APIEndPoint.updateFavoriteMenus
let favoriteMenu: [String: Any] = [
"fvtID": fvtID,
"slNo": slNo,
"menuID": menuID,
"chMenuID": chMenuID,
"sbChMenuID": sbChMenuID,
"title": title,
"url": urlF,
"icon": icon,
"isSelected": isSelected,
"isModified": isModified
]
let params: [[String: Any]] = [favoriteMenu]
APIManager.shared.callDecodableApiRequest1(with: url, method: .post, params: params, showHud: true) { (statusCode, error, model: CommonModel?) in
if model?.status == "ok" {
showSuccessToast(message: model?.message ?? "")
completion(true)
} else {
showErrorToast(message: model?.message ?? model?.status ?? K.Msgs.error)
completion(false)
}
}
}
}
This is APIManager code
class APIManager {
static let shared = APIManager()
typealias CompletionHandler = (_ statusCode: Int, _ error: Error?, _ response: Any?) -> Void
typealias DecodableCompletionHandler<Model: Decodable> = (_ statusCode: Int, _ error: Error?, _ response: Model?) -> Void
func callDecodableApiRequest1<Model: Codable>(with url: String, method: HTTPMethod, params: [[String: Any]]? = nil, headers: HTTPHeaders? = nil, showHud: Bool = false, encoding: ParameterEncoding? = nil, _ completion: @escaping DecodableCompletionHandler<Model>) {
guard let URL = URL(string: url.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? url) else {
print("nURL: ", url)
let err = NSError(domain: "BAD URL", code: 400, userInfo: ["localizedDescription": "Bad URL"])
completion(400, err, nil)
return
}
print("nURL: ", URL.absoluteString)
print("nPARAMS: ", params ?? [])
let defaultHeaders = headers ?? getHeaders()
var encodingTmp = encoding ?? JSONEncoding.default
if encoding == nil {
encodingTmp = method == .get ? URLEncoding.queryString : JSONEncoding.default
}
// Manually encode params if they are provided
var encodedParams: Parameters?
if let params = params {
do {
let jsonData = try JSONSerialization.data(withJSONObject: params)
encodedParams = try JSONSerialization.jsonObject(with: jsonData, options: []) as? Parameters
} catch {
print("Error encoding parameters: (error)")
completion(400, error, nil)
return
}
}
let afRequest = AF.request(URL, method: method, parameters: encodedParams, encoding: encodingTmp, headers: defaultHeaders)
if showHud {
showHUD()
}
afRequest.responseDecodable(of: Model.self) { (dataResponse) in
if showHud {
hideHUD()
}
let statusCode = dataResponse.response?.statusCode ?? 1001
switch dataResponse.result {
case .success(let obj):
print("nResponse of (dataResponse.request?.url?.absoluteString ?? URL.absoluteString) ((method.rawValue)):", dataResponse.data?.toJSON() ?? "nil")
if self.validateAuthrization(statusCode: statusCode, data: dataResponse.data) {
completion(statusCode, nil, obj)
}
case .failure(let error):
print("nError of (dataResponse.request?.url?.absoluteString ?? URL.absoluteString):", error)
print("nResponse:", dataResponse.data?.toJSON() ?? "nil")
print("Status Code:", statusCode)
if self.validateAuthrization(statusCode: statusCode, data: dataResponse.data) {
completion(statusCode, error, nil)
}
}
}
}
}
and calling servicecall like this
Button(action: {
print("whole selectedItem.... (selectedfavMenu)")
favViewModel.updateFavItem(fvtID: 0, slNo: 0, menuID: selectedfavMenu?.menuID ?? 0, chMenuID: 0, sbChMenuID: 0, title: selectedfavMenu?.title ?? "", urlF: "", icon: selectedfavMenu?.icon ?? "", isSelected: true, isModified: true){ status in
if status{
favViewModel.fetchFavList { status in
}
}
}
dismiss()
}
ERROR:
Error of https://api.jdfngjk/App/UpdateFavoriteMenus: responseSerializationFailed(reason: Alamofire.AFError.ResponseSerializationFailureReason.decodingFailed(error: Swift.DecodingError.typeMismatch(Swift.String, Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: “status”, intValue: nil)], debugDescription: “Expected to decode String but found number instead.”, underlyingError: nil))))
Response: {
“status” : 400,
“errors” : {
“” : [
“A non-empty request body is required.”
],
“favoriteMenus” : [
“The favoriteMenus field is required.”
]
},
“title” : “One or more validation errors occurred.”,
“traceId” : “00-d0bf97964d96cc1623946208c00a11f6-372f8d33614eb41a-00”,
“type” : “https://tools.ietf.org/html/rfc7231#section-6.5.1”
}
Status Code: 400