I'm almost new to swift and I'm facing a runtime error which says:
typeMismatch(Swift.Dictionary, Swift.DecodingError.Context(codingPath: [], debugDescription: "Expected to decode Dictionary but found an array instead.", underlyingError: nil))
I have an Array of data that I need to send to the API.
The code below shows the model that the API will accept
Json
{
"items": [
{
"Number": 1,
"ID": 9827
}
]
}
my struct:
struct Itemm : Codable {
var unitNo:Int?
var personId:Int?
enum iItem : Int ,CodingKey{
case unitNo , personId
}
}
struct welcome : Codable {
var items : [Itemm?]
}
typealias welcomeList = [welcome]
the code below shows the way I'm creating my array and trying to send it to Server
var items = [Itemm]()
for indexPath in self.selectedCells {
let data = self.data![indexPath.section]
let contact = data.contacts[indexPath.row]
let newItem = Itemm(unitNo: data.unitNo, personId: contact?.id)
items.append(newItem)
}
// let welcome = welcome(items: items)
print(items)
let welcomee = welcome(items: items)
print(welcomee)
do{
//I found this part on stackoverflow
let dict = try JSONDecoder().decode([String: Int].self, from: JSONEncoder().encode(items))
print("===============")
print(dict)
print("********************")
Presenter.sendSmsForAllTheMembers(AptId: aptId, data: dict)
}
catch let error
{
print(error)
}
I'm using Alamofire and Moya library. does anybody know how should I send my request to API?
func sendSmsForAllTheMembers(AptId:String , data:[String:Any])
{
ApiGenerator.request(targetApi: ApartemanService.sendSms(aptId: AptId, data: data), responseModel: Nil.self, success: { (response) in
if response.response.statusCode == 200 {
self.view?.SendingSmsSuccess()
}else {
do{
var errorMessage = try response.response.mapString()
errorMessage = errorMessage.replacingOccurrences(of: "\"", with: "",
options: NSString.CompareOptions.literal, range:nil)
print("errorMessage =============")
print(errorMessage)
self.view?.SendingSmsFailed(errorMessage: errorMessage)
}catch let error{
print(error)
self.view?.SendingSmsFailed(errorMessage: "خطا در ارتباط با سرور")
}
}
}) { (error) in
self.view?.SendingSmsFailed(errorMessage: "خطا در ارتباط با سرور")
}
}
var items = [Itemm]()is an array, and you are using theJSONEncoderto encode this and send it as a dictionary. You may want to try converting theitemsarray to a dictionary (see here) and determine if that makes a difference. Note that that may lead to parsing issues on the server side, but it'd be interesting to know if that resolves Xcode's error.