Last active
December 5, 2018 20:29
-
-
Save alexpaul/8b2ab0634381f6ce308e3828d0842524 to your computer and use it in GitHub Desktop.
Parsing a JSON file in the App Bundle
This file contains hidden or 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
// 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