I am toying around/learning Swift and JSON atm and have problems correctly casting around my responses.
So, what I am trying to achieve is displaying a list of "posts" via Alamofire request. I have no problems displaying "first-level" json items like the post-ID or the "message", but when it comes to the author array I am kinda lost.
the json response comes in as an Array with no name, hence the first [
[
-{
__v: 1,
_id: "54428691a728c80424166ffb",
createDate: "2014-10-18T17:26:15.317Z",
message: "shshshshshshshhshshs",
-author: [
-{
_id: "54428691a728c80424166ffa",
userId: "543270679de5893d1acea11e",
userName: "foo"
}
]
}
Here is my corresponding VC:
Alamofire.request(.GET, "\(CurrentConfiguration.serverURL)/api/posts/\(CurrentConfiguration.currentUser.id)/newsfeed/\(CurrentConfiguration.currentMode)",encoding:.JSON)
.validate()
.responseJSON {(request, response, jsonData, error) in
let JSON = jsonData as? NSArray
self.loadPosts(JSON!)
}
tableView.delegate = self
tableView.dataSource = self
}
func loadPosts(posts:NSArray) {
for post in posts {
let id = post["_id"]! as NSString!
let message = post["message"]! as NSString!
var authorArray = post["author"]! as? [Author]!
println(authorArray)
var author:Author = Author()
author.userName = "TEST ME"
var postObj:Post = Post()
postObj.id = id
postObj.message = message
postObj.author = author
uppDatesCollection.append(postObj)
}
println(self.uppDatesCollection.count)
dispatch_async(dispatch_get_main_queue()) {
self.tableView.reloadData()
}
}
my Models for Post
class Post {
var id:String!
var message:String!
var createDate: NSDate!
var author:Array<Author>!
init () {
}
}
and Author
class Author {
var id:String?
var userId:String?
var userName:String?
init () {
}
What is the best Approach here? Should you recast the returning Array as a Dictionary and then Access it via .valueforkey? Do you somehow iterate over the array to get this stuff out?
Obviously you can not say author.name = authorArray[3] as String