I had no idea how to parse JSON data using Alamofire. Right now I successfully request the data from web service. The problem is I'm not really sure how to embed/parse json (image) data into UICollectionView
import UIKit
import Alamofire
class PopularViewController: UIViewController,UICollectionViewDataSource, UICollectionViewDelegate {
var users: [AnyObject] = []
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
//#warning Incomplete method implementation -- Return the number of items in the section
return users.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("UserCell", forIndexPath: indexPath) as PopularCollectionViewCell
Alamofire.request(.GET, "http://xxxxx/users.json").responseJSON { (_, _, data, _) in
println(data)
}
return cell
}
override func viewDidLoad() {
super.viewDidLoad()
}
}
Json Data
{
"users": [{
"userId": 1,
"profilePhoto": "https://graph.facebook.com/1301454197/picture?type=large"
}]
}
I already found the solution.
PopularViewController.swift
import UIKit
import Alamofire
class PopularViewController: UIViewController,UICollectionViewDataSource, UICollectionViewDelegate {
var users: [JSON] = []
@IBOutlet var collectionView: UICollectionView!
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
//#warning Incomplete method implementation -- Return the number of items in the section
return users.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("UserCell", forIndexPath: indexPath) as PopularCollectionViewCell
cell.user = self.users[indexPath.row]
return cell
}
override func viewDidLoad() {
super.viewDidLoad()
Alamofire.request(.GET, "xxxxx/users.json").responseJSON { (request, response, json, error) in
if json != nil {
var jsonObj = JSON(json!)
if let data = jsonObj["users"].arrayValue as [JSON]?{
self.users = data
self.collectionView.reloadData()
}
}
}
}
}
PopularCollectionViewCell.swift
import UIKit
import Haneke
class PopularCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var profilePicture:UIImageView!
var user:JSON?{
didSet{
self.setupUser()
}
}
func setupUser(){
if let urlString = self.user?["profilePhoto"]{
let url = NSURL(string: urlString.stringValue)
self.profilePicture.hnk_setImageFromURL(url!)
}
}
}