はじめに
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))
を使えということらしい.