Skip to content

Instantly share code, notes, and snippets.

@alexpaul
Last active December 5, 2018 20:29
Show Gist options
  • Save alexpaul/8b2ab0634381f6ce308e3828d0842524 to your computer and use it in GitHub Desktop.
Save alexpaul/8b2ab0634381f6ce308e3828d0842524 to your computer and use it in GitHub Desktop.
Parsing a JSON file in the App Bundle
// AppleStockService.swift
// PeopleStocks
//
// Created by Alex Paul on 12/5/18.
// Copyright © 2018 Alex Paul. All rights reserved.
//
import Foundation
public enum AppleServiceError: Error {
case resourcePathDoesNotExist
case contentsNotFound
case decodingError(Error)
}
final class AppleStockService {
public static func fetchStocks() throws -> [StockPrice] {
guard let path = Bundle.main.path(forResource: "appleStockInfo", ofType: "json") else {
throw AppleServiceError.resourcePathDoesNotExist
}
guard let json = FileManager.default.contents(atPath: path) else {
throw AppleServiceError.contentsNotFound
}
do {
let stocks = try JSONDecoder().decode([StockPrice].self, from: json)
return stocks
} catch {
throw AppleServiceError.decodingError(error)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment