struct AnimalKeys: Codable{
var names: String?
var taxonomy: Taxonomy
var locations: String?
var characteristics: String?
enum CodingKeys: String, CodingKey{
case names = "name"
case taxonomy = "taxonomy"
case locations = "locations"
case characteristics = "characteristics"
}
}
struct Taxonomy: Codable{
var kingdom: String?
var phylum: String?
var class1: String?
var family: String?
var scientificname: String?
enum CodingKeys: String, CodingKey{
case kingdom = "kingdom"
case phylum = "phylum"
case class1 = "class"
case family = "family"
case scientificname = "scientific_name"
}
//the API function }
func getAnimalApi(names: String) {
let headers = [
"X-RapidAPI-Key": "123e32234234234234234234234234324234243",
"X-RapidAPI-Host": "animals-by-api-ninjas.p.rapidapi.com"
]
let request = NSMutableURLRequest(url: NSURL(string:"https://animals-by-api-ninjas.p.rapidapi.com/v1/animals?name=%5C(names)")! as URL,
cachePolicy: .useProtocolCachePolicy,
timeoutInterval: 10.0)
request.httpMethod = "GET"
request.allHTTPHeaderFields = headers
let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
if (error != nil) {
print(error)
} else {
// request.httpBody = try? JSONSerialization.data(withJSONObject: data, options: .fragmentsAllowed)
let httpResponse = response as? HTTPURLResponse
// print(httpResponse)
print("good")
var result: AnimalKeys?
guard let data = data else{return}
do {
// self.animal = try JSONDecoder().decode([animalss].self, from: data)
let resultss = try JSONSerialization.jsonObject(with: data, options: .allowFragments)
print("sucess: (resultss)")
let newFind = try JSONDecoder().decode(AnimalKeys.self, from: data) as! Array
print("yup: (newFind)")
}
catch {
print(error)
}
}
})
dataTask.resume()
}
The only thing that prints is the resultsss. But the decoding part prints out typeMismatch(Swift.Dictionary<Swift.String, Any>, Swift.DecodingError.Context(codingPath: [], debugDescription: "Expected to decode Dictionary<String, Any> but found an array instead.", underlyingError: nil))
//results function below
{ success: characteristics = {
"average_litter_size" = 1;
color = BrownBlackWhite;
diet = Herbivore;
"favorite_food" = Grass;
habitat = "Tropical jungles and open plains";
lifespan = "12-16 years";
lifestyle = Herd;
"main_prey" = "Grass. Seeds, Flowers";
predators = "Human, Bears, Wildcats";
"skin_type" = Leather;
slogan = "There are around 75 different species!";
"top_speed" = "25 mph";
type = Mammal;
weight = "150-200kg (331-440lbs)";
};
locations = (
Africa,
Asia
);
name = Zebu;
taxonomy = {
class = Mammalia;
family = Bovidae;
genus = Bos;
kingdom = Animalia;
order = Artiodactyla;
phylum = Chordata;
"scientific_name" = "Bos taurus indicus";
};
}