You cannot access data data files in the same way as a random file using NSBundle.pathForResource . Since they can only be defined in Assets.xcassets , you need to initialize an instance of NSDataAsset in order to access its contents:
let asset = NSDataAsset(name: "Colors", bundle: NSBundle.mainBundle()) let json = try? NSJSONSerialization.JSONObjectWithData(asset!.data, options: NSJSONReadingOptions.AllowFragments) print(json)
Note that the NSDataAsset class was introduced as iOS 9.0 and macOS 10.11.
Swift3 version:
let asset = NSDataAsset(name: "Colors", bundle: Bundle.main) let json = try? JSONSerialization.jsonObject(with: asset!.data, options: JSONSerialization.ReadingOptions.allowFragments) print(json)
In addition, NSDataAsset is surprisingly located in UIKit / AppKit, so be sure to import the appropriate structure into your code:
#if os(iOS) import UIKit #elseif os(OSX) import AppKit #endif
source share