Reputation: 1416
I am trying to convert response from PHP to swift Dictionary but I couldn't figure out how to do it.
Swift code
Alamofire.request(requestString, method: .post, parameters: data, encoding:URLEncoding.default, headers: [:]).responseJSON { (response) in
switch response.result {
case .success(_):
if let response = response.result.value as? [String: Any] {
let updatedData = response["existData"] as! NSDictionary
print(updatedData)
let updatedData2 = response["existData"] as? [String: [String: Int]]
print("updatedData2", updatedData2)
var convertData = [String: [String: Int]]()
for key in Array(updatedData.allKeys) {
var convertInsideData = [String: Int]()
if let array = updatedData[key] as? NSDictionary {
for (k, v) in array {
print(k, "-", v)
convertInsideData[k as! String] = v as! Int
}
}
convertData[key as! String] = convertInsideData
}
.....................
First print,
{
All = {
Maybelline = 2;
};
}
updatedData2 Optional(["All": ["Maybelline": 2]])
Maybelline - 2
Second print, then crash in convertInsideData[k as! String] = v as! Int
{
All = {
Maybelline = 2;
Sephora = 2;
};
}
updatedData2 nil
Sephora - 2
Maybelline - 2
Could not cast value of type 'NSTaggedPointerString' (0x10e374c88) to 'NSNumber' (0x10d0ad600).
2017-11-14 23:52:04.939332+0800 LeanCloudStarter[10014:272299] Could not cast value of type 'NSTaggedPointerString' (0x10e374c88) to 'NSNumber' (0x10d0ad600).
Response from PHP should be like this
$existData = array("All"=>array("Maybelline"=>2, "Sephora"=>2));
echo json_encode("existData"=>$existData));
Upvotes: 1
Views: 2079
Reputation: 3939
I suggest you to use optionals, then your Int value seems to be a String in your Json, try:
for (k, v) in array {
print(k, "-", v)
if let stringV = v as? String {
convertInsideData[k as! String] = Int(stringV)
} else if let numberV = v as? NSNumber {
convertInsideData[k as! String] = v.intValue
}
}
Upvotes: 3