Created
August 5, 2016 22:15
-
-
Save charleshkang/ab09fd1a3a9e0d67355c3fc56207ff6f 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
// | |
// PokemonAPI.swift | |
// PokeWhat | |
// | |
// Created by Charles Kang on 8/5/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) | |
} | |
enum Error: ErrorType | |
{ | |
case InvalidJSON | |
} | |
class PokemonAPI { | |
func fetch(completion: Result<[[String:String]]> -> Void) | |
{ | |
let baseURL = "https://pokeapi.co/api/v2/pokemon-species/?limit=151" | |
background { | |
guard let url = NSURL(string: baseURL) else { return } | |
guard let data = try? NSData(contentsOfURL: url, options: []) else { | |
main { completion(.failure(Error.InvalidJSON)) } | |
return | |
} | |
let json = JSON(data: data) | |
let pokemon = self.parsePokemonJSON(json) | |
main { completion(.success(pokemon)) } | |
print(pokemon) | |
} | |
} | |
func parsePokemonJSON(json: JSON) -> [[String:String]] | |
{ | |
var pokemonObjects = [[String:String]]() | |
for (_, result) in json { | |
let results = result["results"].stringValue | |
print(results) | |
let obj: [String:String] = ["results": results] | |
pokemonObjects.append(obj) | |
} | |
return pokemonObjects | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment