Je suis nouveau sur IOS alors cette question peut être pour les débutants. Je sais exactement ce que je veux faire, mais la question est de savoir comment le faire. J'ai des données JSON du dictionnaire comme
{
"restaurants": [
{
"id": 1,
"restaurantName": "Chuks",
"restaurantPicture": "restaurantImages/benards.jpg",
"status": "Working",
"workingDays": "Tuesday to Sunday",
"workingHours": "3pm to 10pm"
},
{
"id": 3,
"restaurantName": "Chuks",
"restaurantPicture": "restaurantImages/benards.jpg",
"status": "Working",
"workingDays": "Tuesday to Sunday",
"workingHours": "3pm to 10pm"
},
{
"id": 4,
"restaurantName": "Chuks",
"restaurantPicture": "restaurantImages/benards.jpg",
"status": "Working",
"workingDays": "Tuesday to Sunday",
"workingHours": "3pm to 10pm"
},
{
"id": 5,
"restaurantName": "Chuks",
"restaurantPicture": "restaurantImages/benards.jpg",
"status": "Working",
"workingDays": "Tuesday to Sunday",
"workingHours": "3pm to 10pm"
},
{
"id": 6,
"restaurantName": "Chuks",
"restaurantPicture": "restaurantImages/benards.jpg",
"status": "Working",
"workingDays": "Tuesday to Sunday",
"workingHours": "3pm to 10pm"
}
]
}
Et j'essaie d'accéder aux tableaux du dictionnaire avec ce code
override func viewDidLoad() {
super.viewDidLoad()
Alamofire.request(URL_GET_DATA).responseJSON { response in
if let json = response.result.value {
let RestaurantArray : NSArray = json as! NSArray
for i in 0..<RestaurantArray.count{
self.restaurant.append(Restaurant(
restaurantPicture: (RestaurantArray[i] as AnyObject).value(forKey: "restaurantPicture") as? String,
restaurantName: (RestaurantArray[i] as AnyObject).value(forKey: "restaurantName") as? String,
status: (RestaurantArray[i] as AnyObject).value(forKey: "status") as? String
))
}
self.tableViewRestaurants.reloadData()
}
}
self.tableViewRestaurants.reloadData()
}
et j'obtiens cette erreur
Could not cast value of type "__NSSingleEntryDictionaryI" (0x1032e6e98) to "NSArray" (0x1032e7f28).
2018-04-16 11:58:29.020876+0000 restaurant[6262:210307] Could not cast value of type "__NSSingleEntryDictionaryI" (0x1032e6e98) to "NSArray" (0x1032e7f28).
Je sais ce que j'essaie de faire en accédant autableaux dans le dictionnaire, mais le problème est de savoir comment s'y prendre. Toutes les aides et critiques sont les bienvenues car je suis prêt à apprendre. Ou est-il possible d'essayer de ne récupérer que les tableaux de la base de données sans le placer dans le dictionnaire de restaurants? Merci a tous
Réponses:
0 pour la réponse № 1//As per above response
override func viewDidLoad() {
super.viewDidLoad()
Alamofire.request(URL_GET_DATA).responseJSON { response in
if let json = response.result.value as! NSDictionary {
let restaurantsArray = json["restaurants"] as! NSArray
for dict in restaurantsArray {
let ID = (dict as! NSDictionary).value(forKey: "id") as? Int
//You can get more data like above
}
self.tableViewRestaurants.reloadData()
}
}
}
0 pour la réponse № 2
Impossible de convertir la valeur de type "__NSSingleEntryDictionaryI" (0x1032e6e98) en "NSArray" (0x1032e7f28)
Il est clair que response.result.value
est un dictionnaire, pas un tableau.
FYI:
Le dictionnaire est représenté par { }
et tableau par [ ]
en JSON.
Mettez à jour votre code comme suit:
if let json = response.result.value as? [String: Any], let arr = json["restaurants"] as? [[String: Any]] {
let RestaurantArray: [[String: Any]] = arr
for dict in RestaurantArray {
if let picture = dict["restaurantPicture"] as? String,
let name = dict["restaurantName"] as? String,
let status = dict["status"] as? String {
let restaurantModal: Restaurant = Restaurant( restaurantPicture: picture, restaurantName: name, status: status)
self.restaurant.append(restaurantModal)
}
}
// Reload table view on main thread (UI related update)
DispatchQueue.main.async {
self.tableViewRestaurants.reloadData()
}
}
0 pour la réponse № 3
Vous pouvez essayer ceci:
var arrExtractedData:NSMutableArray = NSMutableArray()
if let jsonResponse = response.result.value as? [String: Any]{
let arrRestaurants = json["restaurants"] as? [[String: Any]]
for data in arrRestaurants {
let tempDic:NSMutableDictionary = NSMutableDictionary()
let id = dict["id"]
tempDic.setValue(id, forKey: "id")
let restaurantName = dict["restaurantName"]
tempDic.setValue(restaurantName, forKey: "restaurantName")
let restaurantPicture = dict["restaurantPicture"]
tempDic.setValue(restaurantPicture, forKey: "restaurantPicture")
let status = dict["status"]
tempDic.setValue(status, forKey: "status")
let workingDays = dict["workingDays"]
tempDic.setValue(workingDays, forKey: "workingDays")
let workingHours = dict["workingHours"]
tempDic.setValue(workingHours, forKey: "workingHours")
arrExtractedData.add(tempDic)
}
}
print(arrExtractedData) //Extracted Data
0 pour la réponse № 4
Vous devriez utiliser le protocole Codable. Cela facilite vraiment les choses.
Regardez, étant donné ces données
let data = """
{
"restaurants": [
{
"id": 1,
"restaurantName": "Chuks",
"restaurantPicture": "restaurantImages/benards.jpg",
"status": "Working",
"workingDays": "Tuesday to Sunday",
"workingHours": "3pm to 10pm"
},
{
"id": 3,
"restaurantName": "Chuks",
"restaurantPicture": "restaurantImages/benards.jpg",
"status": "Working",
"workingDays": "Tuesday to Sunday",
"workingHours": "3pm to 10pm"
},
{
"id": 4,
"restaurantName": "Chuks",
"restaurantPicture": "restaurantImages/benards.jpg",
"status": "Working",
"workingDays": "Tuesday to Sunday",
"workingHours": "3pm to 10pm"
},
{
"id": 5,
"restaurantName": "Chuks",
"restaurantPicture": "restaurantImages/benards.jpg",
"status": "Working",
"workingDays": "Tuesday to Sunday",
"workingHours": "3pm to 10pm"
},
{
"id": 6,
"restaurantName": "Chuks",
"restaurantPicture": "restaurantImages/benards.jpg",
"status": "Working",
"workingDays": "Tuesday to Sunday",
"workingHours": "3pm to 10pm"
}
]
}
""".data(using: .utf8)!
Et cette structure
struct Response: Codable {
let restaurants: [Restaurant]
struct Restaurant: Codable {
let id: Int
let restaurantName: String
let restaurantPicture: String
let status: String
let workingDays: String
let workingHours: String
}
}
Vous pouvez facilement obtenir le tableau de Restaurant(s)
.
let restaurants = try? JSONDecoder().decode(Response.self, from: data).restaurants