Created
June 15, 2016 16:10
-
-
Save charleshkang/1c9f8c489a65e7ef6a34df3740b9517e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// MainViewController.swift | |
// Badges | |
// | |
// Created by Charles Kang on 6/14/16. | |
// Copyright © 2016 Charles Kang. All rights reserved. | |
// | |
import UIKit | |
import SwiftyJSON | |
import SDWebImage | |
class MainViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate { | |
var objects = [[String: String]]() | |
override func viewDidLoad() | |
{ | |
super.viewDidLoad() | |
self.parseBadgeJSON() | |
} | |
func parseBadgeJSON () | |
{ | |
let jsonURL = "http://www.khanacademy.org/api/v1/badges" | |
if let url = NSURL(string: jsonURL) { | |
if let data = try? NSData(contentsOfURL: url, options: []) { | |
let json = JSON(data: data) | |
fetchBadgeJSON(json) | |
} | |
} | |
} | |
func fetchBadgeJSON(json: JSON) | |
{ | |
for (_, result) in json { | |
let title = result["description"].stringValue | |
let smallIcon = result["icons"]["small"].stringValue | |
let category = result["badge_category"].stringValue | |
let points = result["points"].stringValue | |
let obj = ["title": title, "icon": smallIcon, "category": category, "points": points] | |
objects.append(obj) | |
} | |
} | |
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int | |
{ | |
return self.objects.count | |
} | |
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell | |
{ | |
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cellIdentifier", forIndexPath: indexPath) as! BadgeCollectionViewCell | |
cell.layer.borderColor = UIColor.blackColor().CGColor | |
cell.layer.borderWidth = 1 | |
cell.layer.cornerRadius = 10 | |
let orderedDict = objects.sort { | |
if ($0["category"] == $1["category"]) { | |
return $0["category"] < $1["category"] | |
} else { | |
return $0["category"] < $1["category"] | |
} | |
} | |
let object = orderedDict[indexPath.row] | |
cell.badgeLabel.text = object["title"] | |
let imageURL: NSURL? = NSURL(string: object["icon"]!) | |
if let url = imageURL { | |
cell.badgeImage.sd_setImageWithURL(url) | |
} | |
return cell | |
} | |
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) | |
{ | |
print("You selected badge #\(indexPath.row)") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment