LoginSignup
27
12

More than 5 years have passed since last update.

iOSプロジェクトのテストバンドルに存在するファイルを取得する

Last updated at Posted at 2017-01-04

Xcode 9.2, Swift 4で動作確認済み

アプリケーションバンドルに存在するファイルを取得する

アプリケーションバンドルに存在するファイルは、以下のコードで取得できる。

let path = Bundle.main.path(forResource: "foo", ofType: "json")
let data: NSData? = try? NSData(contentsOfFile: path!, options: .uncached)

ユニットテスト等でテストバンドルに存在しているファイルを取得するにはこの方法ではうまくいかない。

テストバンドルに存在するファイルを取得する

以下の方法で取得できる。

let testBundle = Bundle(for: type(of: self))
let path = testBundle.url(forResource: "bar", withExtension: "json")
let data: NSData? = try? NSData(contentsOf: path!, options: .uncached)

プロジェクト構成

resource.png

参考:
http://stackoverflow.com/questions/19309092/nsurl-to-file-path-in-test-bundle-with-xctest

27
12
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
27
12