So far I only had to deal with simple JSON arrays with only a single array. I have now combined 2 arrays together so I can get my user data and all the reviews for that user:
[
{
"user_id": "16",
"name": "Jonh",
"lastName": "appleseed",
"username": "[email protected]",
"sex": "male",
"image_url": "",
"review": [
{
"reviewID": "4",
"merchant_id": "17",
"rating": "5",
"user_id": "16",
"comments": "Very good customer. Strongly suggested",
"date": "0000-00-00",
"reviewYear": "",
"publish": "1"
},
{
"reviewID": "8",
"merchant_id": "16",
"rating": "2",
"user_id": "16",
"comments": "Automatic review due to "NO SHOW" without informing the merchant",
"date": "0000-00-00",
"reviewYear": "",
"publish": "1"
}
]
}
]
before I added the reviews my model looked like this:
import Foundation
class Users {
let userImage:String?
let name:String?
let sex:String?
let image_url:String?
init(dictionary:NSDictionary) {
userImage = dictionary["userImage"] as? String
name = dictionary["name"] as? String
sex = dictionary["sex"] as? String
image_url = dictionary["image_url"] as? String
}
}
func loadUser(completion:(([Users])-> Void), userId: String){
let myUrl = NSURL(string: "http://www.myWebSite.com/api/v1.0/users.php")
let request = NSMutableURLRequest(URL: myUrl!)
request.HTTPMethod = "POST"
let postString = "user_id=\(userId)"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request)
{ data, response, error in
if error != nil {
print("error\(error)")
} else {
do {
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as! NSArray
print(json)
var users = [Users]()
for user in json{
let user = Users(dictionary: user as! NSDictionary)
users.append(user)
let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT
dispatch_async(dispatch_get_global_queue(priority, 0 )){
dispatch_async(dispatch_get_main_queue()){
completion(users)
}
}
}
} catch{
}
}
}
task.resume()
}
which I could then used in my viewController:
func loadModel() {
let loadingNotification = MBProgressHUD.showHUDAddedTo(self.view, animated: true)
loadingNotification.mode = MBProgressHUDMode.Indeterminate
loadingNotification.labelText = "updating your deals..."
users = [Users]()
let api = Api()
api.loadUser(didLoadUsers , userId: "16")
}
func didLoadUsers(users:[Users]){
self.users = users
self.tableView.reloadData()
MBProgressHUD.hideAllHUDsForView(self.view, animated: true)
}
Can I get the review field so I can present it in a table view controller?