Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
457 views
in Technique[技术] by (71.8m points)

swift - uncaught exception 'NSInvalidArgumentException' when selecting an Image

In my current app project, I have the ability to select an image. The functionality has been working well for a while. However, I am now getting the following error when I click on the image select button. I have tried to figure the the source of the error, but I can't seem to find it.

I suspect that the issue has nothing to do with the image select functionality, but is related to something else in the app. When I take the same code into a new app project, the image select functionality works fine. Please help point me in the right direction.

2021-01-28 08:43:54.883769-0500 Social Squash[11718:144431] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[__NSDictionaryM setObject:forKey:]: object cannot be nil (key: NSColor)'
*** First throw call stack:
(
    0   CoreFoundation                      0x00007fff20421af6 __exceptionPreprocess + 242
    1   libobjc.A.dylib                     0x00007fff20177e78 objc_exception_throw + 48
    2   CoreFoundation                      0x00007fff2049e77f _CFThrowFormattedException + 194
    3   CoreFoundation                      0x00007fff204aa035 -[__NSDictionaryM setObject:forKey:].cold.3 + 0
    4   CoreFoundation                      0x00007fff2048e134 -[__NSDictionaryM setObject:forKey:] + 922
    5   UIKitCore                           0x00007fff24204dd4 -[_UIAppearanceRecorder _recordInvocation:withClassName:containerClassNames:traitCollection:selectorString:forRemoteProcess:] + 2705
    6   UIKitCore                           0x00007fff241ff355 __54+[_UIAppearance _recordersExcludingSource:withWindow:]_block_invoke + 891
    7   CoreFoundation                      0x00007fff2037b9e3 __NSDICTIONARY_IS_CALLING_OUT_TO_A_BLOCK__ + 7
    8   CoreFoundation                      0x00007fff2048f06f -[__NSDictionaryM enumerateKeysAndObjectsWithOptions:usingBlock:] + 225
    9   UIKitCore                           0x00007fff241fefc8 +[_UIAppearance _recordersExcludingSource:withWindow:] + 131
    10  UIKitCore                           0x00007fff24ad18b9 UIViewServiceCurrentAppearanceSerializedRepresentations + 84
    11  UIKitCore                           0x00007fff24aa3908 +[_UIRemoteViewController _requestViewController:traitCollection:fromServiceWithBundleIdentifier:service:connectionHandler:] + 353
    12  UIKitCore                           0x00007fff24aa3773 +[_UIRemoteViewController requestViewControllerWithService:traitCollection:connectionHandler:] + 79
    13  UIKitCore                           0x00007fff24087917 __146-[NSExtension(UIViewControllerAdditions) _instantiateViewControllerWithInputItems:asAccessory:traitCollection:listenerEndpoint:connectionHandler:]_block_invoke_2 + 554
    14  libdispatch.dylib                   0x000000010c11d7ec _dispatch_call_block_and_release + 12
    15  libdispatch.dylib                   0x000000010c11e9c8 _dispatch_client_callout + 8
    16  libdispatch.dylib                   0x000000010c12ce75 _dispatch_main_queue_callback_4CF + 1152
    17  CoreFoundation                      0x00007fff2038fdbb __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 9
    18  CoreFoundation                      0x00007fff2038a63e __CFRunLoopRun + 2685
    19  CoreFoundation                      0x00007fff203896d6 CFRunLoopRunSpecific + 567
    20  GraphicsServices                    0x00007fff2c257db3 GSEventRunModal + 139
    21  UIKitCore                           0x00007fff24696cf7 -[UIApplication _run] + 912
    22  UIKitCore                           0x00007fff2469bba8 UIApplicationMain + 101
    23  Social Squash                       0x0000000104c01d1b main + 75
    24  libdyld.dylib                       0x00007fff2025a3e9 start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[__NSDictionaryM setObject:forKey:]: object cannot be nil (key: NSColor)'
terminating with uncaught exception of type NSException
CoreSimulator 732.18.6 - Device: iPhone 12 Pro Max (FCAFC159-47E8-4687-A7CB-9A6300821E09) - Runtime: iOS 14.4 (18D46) - DeviceType: iPhone 12 Pro Max

My code is as follows:

   import SwiftUI

struct ImagePickerExampleView: View {

    @State var showImagePicker: Bool = false
    @State var image: UIImage?

    var body: some View {
        VStack {
            if image != nil {
                Image(uiImage: image!)
                    .resizable()
                    .aspectRatio(contentMode: .fit)
            }
            Button("Pick image") {
                self.showImagePicker.toggle()
            }
        }
        .sheet(isPresented: $showImagePicker) {
            ImagePickerView(sourceType: .photoLibrary) { image in
                self.image = image
            }
        }
    }
}

struct ImagePickerExampleView_Previews: PreviewProvider {
    static var previews: some View {
        ImagePickerExampleView()
    }
}

Here is the code for the UIController

public struct ImagePickerView: UIViewControllerRepresentable {

    private let sourceType: UIImagePickerController.SourceType
    private let onImagePicked: (UIImage) -> Void
    @Environment(.presentationMode) private var presentationMode

    public init(sourceType: UIImagePickerController.SourceType, onImagePicked: @escaping (UIImage) -> Void) {
        self.sourceType = sourceType
        self.onImagePicked = onImagePicked
    }

    public func makeUIViewController(context: Context) -> UIImagePickerController {
        let picker = UIImagePickerController()
        picker.sourceType = self.sourceType
        picker.delegate = context.coordinator
        return picker
    }

    public func updateUIViewController(_ uiViewController: UIImagePickerController, context: Context) {}

    public func makeCoordinator() -> Coordinator {
        Coordinator(
            onDismiss: { self.presentationMode.wrappedValue.dismiss() },
            onImagePicked: self.onImagePicked
        )
    }

    final public class Coordinator: NSObject, UINavigationControllerDelegate, UIImagePickerControllerDelegate {

        private let onDismiss: () -> Void
        private let onImagePicked: (UIImage) -> Void

        init(onDismiss: @escaping () -> Void, onImagePicked: @escaping (UIImage) -> Void) {
            self.onDismiss = onDismiss
            self.onImagePicked = onImagePicked
        }

        public func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) {
            if let image = info[.originalImage] as? UIImage {
                self.onImagePicked(image)
            }
            self.onDismiss()
        }

        public func imagePickerControllerDidCancel(_: UIImagePickerController) {
            self.onDismiss()
        }

    }

}
question from:https://stackoverflow.com/questions/65938867/uncaught-exception-nsinvalidargumentexception-when-selecting-an-image

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The issue was in an init() statement that was setting the NavigationBar text title. I had the following statement:

UINavigationBar.appearance().titleTextAttributes = [.foregroundColor : dim.navbar.fontColor]

I was missing the .uiColor() and end of the the .fontColor

 UINavigationBar.appearance().titleTextAttributes = [.foregroundColor : dim.navbar.fontColor.uiColor()]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...