LoginSignup
2
0

More than 5 years have passed since last update.

Swift:リソースを含んだFrameworkを作成するときのTips

Posted at

はじめに

CSVのファイルを利用したオリジナルのFrameworkを作成する際に,リソースが読み込めない問題にぶつかった.
解決策を記述する

Bad

if let filePath = Bundle.main.path(forResource: "sample", ofType: "csv") {
    do {
        let str = try String(contentsOfFile: filePath, encoding: String.Encoding.utf8)
        //処理
    } catch let error {
        Swift.print(error.localizedDescription)
    }
}

Good

if let filePath = Bundle(for: type(of: self)).path(forResource: "sample", ofType: "csv") {
    do {
        let str = try String(contentsOfFile: filePath, encoding: String.Encoding.utf8)
        //処理
    } catch let error {
        Swift.print(error.localizedDescription)
    }
}

要はBundle.mainではなくBundle(for: type(of: self))を使えということらしい.

2
0
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
2
0