Reputation: 193
I have a POST request that is illustrated below. I need some help on how to be able to use the response data. The response I am getting is in a form of a dictionary. What is the best practice to use here? The error message I am getting is:
Cannot assign value of type 'DataResponse' to type 'String'
func getRequest(){
let urlString = "http://scissors.pythonanywhere.com/getRequest"
Alamofire.request(urlString, method: .post, parameters: ["date": self.weekDays[self.itemSelectedIndex]],encoding: JSONEncoding.default, headers: nil).responseString {
response in
switch response.result {
case .success:
print(response)
var backToString = String(data: response, encoding: String.Encoding.utf8) as String?
break
case .failure(let error):
print(error)
}
}
}
I tried self.bookings = response as! String
but it gives me a warning saying it will fail. Also tried this: Alamofire in Swift: converting response data in usable JSON dictionary with no luck.
EDIT
This is the print i get from response.
SUCCESS: {
"10:00" = {
booked = false;
name = "";
number = "";
};
"10:30" = {
booked = false;
name = "";
number = "";
};
"11:00" = {
booked = false;
name = "";
number = "";
};
}
Upvotes: 2
Views: 3137
Reputation: 193
I actually ended up using this method which was very simple and easy. In my case bookings was declared like this: var bookings: NSDictionary = [:]
func getRequest(){
let urlString = "http://scissors.pythonanywhere.com/getRequest"
Alamofire.request(urlString, method: .post, parameters: ["date": self.weekDays[self.itemSelectedIndex]],encoding: JSONEncoding.default, headers: nil).responseJSON {
response in
switch response.result {
case .success(let JSON):
self.bookings = JSON as! NSDictionary
self.tableView.reloadData()
break
case .failure(let error):
print(error)
}
}
}
Upvotes: 3
Reputation: 1229
Now that you have the JSON representation, you should be able to do something like this:
if let dict = response as? [String:Any]{
if let obj = dict["10:00"] as? [String:Any]{
let booked = obj["booked"] as? Bool ?? false
print("booked: \(booked)");
}
}
Upvotes: 0