let stringPath = Bundle.main.path(forResource: "food-storage", ofType: "jpeg")!
let urlPath = Bundle.main.url(forResource: "food-storage", withExtension: "jpeg")!
print(stringPath)
print(urlPath)
check if the resource is in Targets / Build Phases / Copy Bundle Resources
.
Image
use bundle image
if Bundle.main.path(forResource: "food-storage", ofType: "jpeg") != nil {
Image(uiImage: UIImage(named: "food-storage.jpeg")!)
}
Text use bundle
let goodFile = Bundle.main.url(forResource: "good", withExtension: "txt")!
let data = try! Data(contentsOf: goodFile)
let string = String(data: data, encoding: .utf8)!
Text(string)
let goodFile = Bundle.main.url(forResource: "good", withExtension: "txt")!
let str = try! String(contentsOf: goodFile)
Text(str)
Text use dictionary
good.txt
Hello
Chime
Guarantor
ContentView.swift
struct ContentView: View {
var allWords: [String] = ["Ok"]
init() {
let goodFile = Bundle.main.url(forResource: "good", withExtension: "txt")!
let str = try! String(contentsOf: goodFile)
allWords = str.components(separatedBy: "\n")
print(allWords)
}
var body: some View {
ForEach(0..<allWords.count) { idx in
Text(allWords[idx])
}
}
}