Search code examples
swiftfunctiondatenullunwrapping

Why Fatal error: Unexpectedly found NIL while unwrapping an Optional value


I would like to read metadata from a video. The console shows me the creation date from the metadata of the file. I may be extracting the date (via string) incorrectly. Why do I get the fatal error? Thank you very much!

    func getVideoMetadataDate (srcPath: String, itemSrc: String) async -> Date {
        
        let dF = DateFormatter()
        dF.dateFormat = "yyyy:MM:dd HH:mm:ss"
        
        let returnValue: String = "1975:01:01 00:00:00"
        
        
        let itemSrcURL = URL(fileURLWithPath: srcPath + "/" + String(itemSrc))
        let asset = AVAsset(url: itemSrcURL)
        
        do {
            for format in try await asset.load(.availableMetadataFormats) {
                
                let metadata = try await asset.loadMetadata(for: format)

                let dateItems = AVMetadataItem.metadataItems(from: metadata, filteredByIdentifier: .commonIdentifierCreationDate)
                guard let item = dateItems.first else { return dF.date(from: returnValue)! }
                let dateCreate = item.value as! String
                print(dateCreate) // Console -> = "2024-02-13T13:22:30+0100"
                return dF.date(from: dateCreate)! // Here -> Thread 9: Fatal error: Unexpectedly found nil while unwrapping an Optional value
            }
        } catch {
            return dF.date(from: returnValue)!
        }
        return dF.date(from: returnValue)!
    }

I would like the function to return the creation date from the metadata.


Solution

  • I call the ! force unwrap operator the "crash if nil" operator. That is what it does. Any time you use it and the optional you are force-unwrapping contains a nil, your app will crash. You should avoid it completely until you really, really understand optionals, and then probably still avoid it.

    As Alexander says in his comment, your input date string does not appear to match the format you've given your DateFormatter. Code that depends on the format of external data is especially fragile, and you should really, REALLY avoid force-unwrapping code that relies on input data formatting.

    Look into if let, guard let, the ?? "nil coalescing operator", and other techniques for safely dealing with nil optionals. Even if you fix your date formatter problem I would still suggest getting rid of the force unwrap and using one of those other techniques (or even making your date field an Optional that is nil if your code can't parse the date correctly, and then coding defensively elsewhere.)