Search code examples
iosswiftuiimagepickercontroller

Crash _assertionFailure with imagePickerController


I've following crash log from crashlytics and code below.

I'm aware that fatalError will crash app. What I wanted to ask is that if there is anything wrong with the code snippet which may be causing error and if we can avoid it?

Crashed: com.apple.main-thread
0  libswiftCore.dylib             0x1b013b5c4 _assertionFailure(_:_:file:line:flags:) + 800
1  MyApp                0x1045d7d34 specialized ChatController.imagePickerController(_:didFinishPickingMediaWithInfo:) + 1632 (ChatController.swift:1632)
2  MyApp                0x1045d2c1c @objc ChatController.imagePickerController(_:didFinishPickingMediaWithInfo:) + 4343098396 (<compiler-generated>:4343098396)
3  UIKitCore                      0x1a63368bc -[UIImagePickerController _imagePickerDidCompleteWithInfo:] + 120
4  UIKitCore                      0x1a63361b8 __60-[UIImagePickerController didSelectMediaWithInfoDictionary:]_block_invoke + 48
5  libdispatch.dylib              0x1a25a2ec4 _dispatch_call_block_and_release + 32
6  libdispatch.dylib              0x1a25a433c _dispatch_client_callout + 20
7  libdispatch.dylib              0x1a25b0600 _dispatch_main_queue_callback_4CF + 832
8  CoreFoundation                 0x1a287f41c __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 16
9  CoreFoundation                 0x1a287a034 __CFRunLoopRun + 1708
10 CoreFoundation                 0x1a2879660 CFRunLoopRunSpecific + 480
11 GraphicsServices               0x1acc8a604 GSEventRunModal + 164
12 UIKitCore                      0x1a6a4e15c UIApplicationMain + 1944
13 MyApp                0x1043f37a0 main + 21 (ProfileViewController.swift:21)
14 libdyld.dylib                  0x1a26f51ec start + 4

ChatController.swift:

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any])
{
    
    guard let selectedImage = info[.originalImage] as? UIImage else {
        // Following line is 1632
        fatalError("Error: Expected a dictionary containing an image, but was provided the following: \(info)")
    }
    // other code...
}

Solution

  • It's obvious you're getting the crash because you're asking the compiler to do so with fatalError. If you're trying to avoid the crash then remove the fatalError and maybe handle the event where originalImage is unavailable.

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        guard let selectedImage = info[.originalImage] as? UIImage else {
            print("Error: Expected a dictionary containing an image, but was provided the following: \(info)")
            // maybe set a placeholder image to the UIImageView
            return
        }
        // other code...
    }