Created
June 15, 2016 17:36
-
-
Save charleshkang/54cb0d672f62a4f6f28ac7abb5724677 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
// | |
// BadgeAPI.swift | |
// Badges | |
// | |
// Created by Charles Kang on 6/15/16. | |
// Copyright © 2016 Charles Kang. All rights reserved. | |
// | |
import Foundation | |
import SwiftyJSON | |
public func main(function: Void -> Void) { | |
dispatch_async(dispatch_get_main_queue(), function) | |
} | |
public func background(function: Void -> Void) { | |
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), function) | |
} | |
enum Result<T> { | |
case success(T) | |
case failure(ErrorType) | |
} | |
class BadgeAPI { | |
public func fetch(completion: Result<[[String: String]]> -> Void) { | |
let jsonURL = "http://www.khanacademy.org/api/v1/badges" | |
background { | |
if let url = NSURL(string: jsonURL) { | |
if let data = try? NSData(contentsOfURL: url, options: []) { | |
let json = JSON(data: data) | |
let badges = self.parseBadgeJSON(json) | |
completion(.success(badges)) | |
} | |
} | |
} | |
} | |
public func parseBadgeJSON(json: JSON) -> [[String: String]] | |
{ | |
var objects = [[String: String]]() | |
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) | |
} | |
return objects | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment