Search code examples
swiftalamofireuserdefaults

libc++abi.dylib: terminating with uncaught exception of type NSException Alamofire


I am sending images to the server using alamofire. If parameters ;

    let parameters: Parameters = [
        "userID": "1",
        "acToken": "acToken"
    ]

working but parameters ;

    let parameters: Parameters = [
        "userID": userID,
        "acToken": acToken ?? ""
    ]

not working. error = libc++abi.dylib: terminating with uncaught exception of type NSException

I'm using swift4, alamofire 4, Xcode 9.2

My upload method :

func profilePhotoUpload(){
        let defaults = UserDefaults.standard
        let userID = defaults.integer(forKey: "userID")
        let acToken = defaults.string(forKey: "acToken")
        print("\(userID) - \(acToken ?? "")")

            // add UI related changes here
            let image = self.profilePhoto.image

            let parameters: Parameters = [
                "userID": userID,
                "acToken": acToken ?? ""
            ]

            Alamofire.upload(multipartFormData: { (multipartFormData) in
                multipartFormData.append(UIImageJPEGRepresentation(image!, 1)!, withName: "photo_path", fileName: "swift_file.jpeg", mimeType: "image/jpeg")
                for (key, value) in parameters {
                    multipartFormData.append((value as AnyObject).data(using: String.Encoding.utf8.rawValue)!, withName: key)
                }
            }, to:"http......")
            { (result) in
                switch result {
                case .success(let upload, _, _):

                    upload.uploadProgress(closure: { (progress) in
                        //Print progress
                    })

                    upload.responseJSON { response in
                        print(response.result)
                        //print response.result
                    }

                case .failure(let encodingError):
                    print(encodingError.localizedDescription)
                    break
                    //print encodingError.description
                }
            }
    }

error log :

VoiceStage[33099:1632858] -[NSCFNumber dataUsingEncoding:]: unrecognized selector sent to instance 0xb000000000000013 2018-03-26 16:20:16.686009+0300 VoiceStage[33099:1632858] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFNumber dataUsingEncoding:]: unrecognized selector sent to instance 0xb000000000000013' *** First throw call stack: ( 0 CoreFoundation 0x000000010520f12b __exceptionPreprocess + 171 1 libobjc.A.dylib 0x00000001048a3f41 objc_exception_throw + 48 2 CoreFoundation 0x0000000105290024 -[NSObject(NSObject) doesNotRecognizeSelector:] + 132 3 CoreFoundation 0x0000000105191f78 ___forwarding_ + 1432 4 CoreFoundation 0x0000000105191958 _CF_forwarding_prep_0 + 120 5 VoiceStage 0x0000000103d09a7a T010VoiceStage27ProfileDetailViewControllerC18profilePhotoUploadyyFy9Alamofire17MultipartFormDataCcfU + 1354 6 VoiceStage 0x0000000103d0f9a4 _T010VoiceStage27ProfileDetailViewControllerC18profilePhotoUploadyyFy9Alamofire17MultipartFormDataCcfU_TA + 84 7 Alamofire 0x000000010415a994 _T09Alamofire14SessionManagerC6uploadyyAA17MultipartFormDataCc09multipartfG0_s6UInt64V14usingThresholdAA21URLRequestConvertible_p4withyAC0efG14EncodingResultOcSg18encodingCompletiontFyycfU_ + 212 8 Alamofire 0x000000010415e2bc _T09Alamofire14SessionManagerC6uploadyyAA17MultipartFormDataCc09multipartfG0_s6UInt64V14usingThresholdAA21URLRequestConvertible_p4withyAC0efG14EncodingResultOcSg18encodingCompletiontFyycfU_TA + 156 9 Alamofire 0x00000001040e0599 _T0Ix_IyB_TR + 41 10 libdispatch.dylib 0x000000010a10d2f7 _dispatch_call_block_and_release + 12 11 libdispatch.dylib 0x000000010a10e33d _dispatch_client_callout + 8 12 libdispatch.dylib 0x000000010a11a3a2 _dispatch_root_queue_drain + 1444 13 libdispatch.dylib 0x000000010a119da0 _dispatch_worker_thread3 + 132 14 libsystem_pthread.dylib 0x000000010a5d41ca _pthread_wqthread + 1387 15 libsystem_pthread.dylib 0x000000010a5d3c4d start_wqthread + 13 ) libc++abi.dylib: terminating with uncaught exception of type NSException (lldb)


Solution

  • -[NSCFNumber dataUsingEncoding:]: unrecognized selector sent to instance
    

    The error message is saying: I tried to call a method dataUsingEncoding: (Objective-C version one), that is in Swift data(using:) on a NSNumber object. I can't, I crashed. So it means that at some point you think that you are using a String object when in fact it's a Number one (or a conversion to Number from an Int).

    multipartFormData.append((value as AnyObject).data(using: String.Encoding.utf8.rawValue)!, withName: key)
    

    You assume that value responds to data(using:). Well in fact, it should be more (value as String). Managing more case would be to test the class of value. If it's a String object, use data(using:), if it's already a Data object simply put value.

    In pseudo code :

    let valueToSet;
    if value is a String Object {
       valueToSet = (value as String).data(using:.utf8)
    } else if value is a Data Object {
       valueToSet = value
    } else if value is a Number Object {
       valueToSet = String(initWithNumber:value).data(using:.utf8)
    } else ... ?
    
        multipartFormData.append(valueToSet, withName: key)
    

    You also write:

    let parameters: Parameters = [
        "userID": userID,
        "acToken": acToken ?? ""
    ]
    

    So after all this explanation about the error: userID is not a String or acToken is not a String but an Int. According to the names, I tend to say that userID is an Int.