Question

I am grabbing images from the users' contacts in their iOS Address Book/Contacts.app. And putting them in a dictionary to upload as JSON.

I am getting the following error:

2012-12-05 10:38:01.286 ContactsApp[6247:713f] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Invalid type in JSON write (__NSCFData)'
*** First throw call stack:
(0x2de6012 0x286ce7e 0x2de5deb 0x20926fe 0x2096b21 0x2dd3cdf 0x2dd387d 0x2dd37c5 0x20966fa 0x209262d 0x2096b21 0x2dd3cdf 0x2dd387d 0x2dd37c5 0x20966fa 0x209262d 0x20969af 0x2ddfe7c 0x2ddfa16 0x2ddf925 0x20968b8 0x2092679 0x2096b21 0x2dd3cdf 0x2dd387d 0x2dd37c5 0x20966fa 0x209262d 0x20923bd 0x209579c 0x1cad5 0x67475 0x66a87 0x14399cd 0x746008f 0x3dc253f 0x3dd4014 0x3dc52e8 0x3dc5450 0x90e36e12 0x90e1ecca)
libc++abi.dylib: terminate called throwing an exception

I've using the following code:

if (ABPersonHasImageData(addressBookContact)) {
    NSMutableDictionary *imageDictionary = [NSMutableDictionary dictionary];
    NSData *thumbnailImageData = (__bridge NSData *)ABPersonCopyImageDataWithFormat(addressBookContact, kABPersonImageFormatThumbnail);
    NSData *originalImageData = (__bridge NSData *)ABPersonCopyImageDataWithFormat(addressBookContact, kABPersonImageFormatOriginalSize);
    if (thumbnailImageData) [imageDictionary setObject:thumbnailImageData forKey:@"thumbnailImage"];
    if (originalImageData) [imageDictionary setObject:originalImageData forKey:@"originalImage"];
    [contactDictionary setObject:imageDictionary forKey:@"image"];
}

The error occurs when I am trying to place the array into this request:

[addressBookArray addObject:contactDictionary];
if ([addressBookArray count] % 15 == 0) {
    // I'm using AFNetworking
    [[APIClient sharedClient] requestWithMethod:@"POST" path:@"cmd/addContact" parameters:@{ @"addressBookEntries" : addressBookArray }];
    [addressBookArray removeAllObjects];
}
Was it helpful?

Solution

Your problem is that you are attempting to put NSData objects into a JSON object. Instead of adding the image data to the imageDictionary, add the base64 encoding of the images to the imageDictionary and you should have no problem.

Matt Gallagher has a handy class for handling base64 here: http://www.cocoawithlove.com/2009/06/base64-encoding-options-on-mac-and.html

OTHER TIPS

Looks like AFNetworking is trying to parse your parameters into JSON, but you're passing it an NSData. Although your passing it an NSDictionary, which is valid, those nested types need to be either other NSDictionaries, NSArrays, NSStrings, and NSNumbers. If you want to append image NSDatas, you have to use a different content-type and append the image data.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top