Search code examples
iosswiftuiwebviewwkwebview

(Swift) Error when trying to load a local .css file


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)

Solution

  • 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)
        }