0

In my app I have a folder named "CSS" with file named "style.css" in it.
When I try to load it, I get this error :

Fatal error: Unexpectedly found nil while unwrapping an Optional value

This is the code where I am trying to load it :

let path = Bundle.main.path(forResource: "style", ofType: "css", inDirectory: "CSS")!
let cssString = try! String(contentsOfFile: path).trimmingCharacters(in: .whitespacesAndNewlines)
Jawad Ali
  • 13,556
  • 3
  • 32
  • 49
faris97
  • 402
  • 4
  • 24
  • Does this answer your question? [What does "Fatal error: Unexpectedly found nil while unwrapping an Optional value" mean?](https://stackoverflow.com/questions/32170456/what-does-fatal-error-unexpectedly-found-nil-while-unwrapping-an-optional-valu) – Ahmad Alfy Feb 10 '20 at 17:11
  • 1 - make sure you included `CSS/style.css` (case-sensitive) in resource bundle at build time; 2 - never force-unwrap, check for errors instead with if or guard, e.g. `guard let path = Bundle.main.path(...)` – timbre timbre Feb 10 '20 at 17:17
  • The problem was in CSS folder. Everything works when I remove my style.css from CSS folder. – faris97 Feb 11 '20 at 08:49

1 Answers1

2

Ensure your file is present in the Build Phases > Copy Bundle Resources list

dont force unwrap , check for errors like this

   guard Bundle.main.path(forResource: "style", ofType: "CSS") != nil else {
        return
    }

    do {

    } catch let error {
        print(error)
    }
Jawad Ali
  • 13,556
  • 3
  • 32
  • 49