-2

I guess this is basic Swift, so I'm a bit embarrassed to ask:

In my app, I download a plist file from a server as such:

 Alamofire.download(url, to: destination).response { response in
       if let url = response.destinationURL {
                    self.holidays = NSDictionary(contentsOf: url)!
                }
            }

The file is a valid file, and it is succesfully dowloaded and sitting physically in my Documents folder.

However, the app crashes on

self.holidays = NSDictionary(contentsOf: url)!

saying

Fatal error: Unexpectedly found nil while unwrapping an Optional value

What gives?

Sjakelien
  • 2,255
  • 3
  • 25
  • 43
  • `NSDictionary(contentsOf: url)` can return `nil` which would trigger that crash. You may want to check the file actually exists first and/or adjust the path if needed. – CodingNagger Oct 23 '18 at 11:18
  • Can we assume that you already read [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) – Martin R Oct 23 '18 at 11:25
  • @Martin yes you can – Sjakelien Oct 23 '18 at 11:27
  • 2
    Well, then you know the forced unwrapping crashes if `NSDictionary(contentsOf: url)` is nil – did you investigate that possibility? – Martin R Oct 23 '18 at 11:29
  • 1
    Possible duplicate of [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) – Desdenova Oct 23 '18 at 11:34

2 Answers2

1

Your NSDictionary is failing to initialize, so when you try to force unwrap it (with the exclamation mark) it fails and crashes.

Oni_01
  • 470
  • 5
  • 12
0

Try something like this:

if let dictionary = NSDictionary(contentsOf: url) {
    self.holidays = dictionary
}

Alternatively you can use the guard statement:

guard let dictionary = NSDictionary(contentsOf: url) else {
    print("NSDictionary failed to initialise")
    return
}

self.holidays = dictionary
henrik-dmg
  • 1,448
  • 16
  • 23