I’m using URLScheme and I need to send serialized NSDictionary from my app A to my app B.
In the app A, I’m using NSKeyedArchiver to serialize my NSDictionary into a NSData
NSDictionary *myDictionary = [NSDictionary dictionaryWithObjectsAndKeys:@"This is value 1", @"key1",
@"value 2", @"key2",
@"value3", @"key3",
@"", @"key4",
@"value5", @"key5",
@"value 6", @"key6",
nil];
NSMutableData *data = [[NSMutableData alloc] init];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
[archiver encodeObject:myDictionary];
[archiver finishEncoding];
[archiver release];
NSString *bytes = [[[NSString alloc] initWithData:data
encoding:NSASCIIStringEncoding] autorelease];
In the app B, I’m using NSKeyedUnarchiver
NSData *data = [[NSString stringWithFormat:@"%@", val] dataUsingEncoding:NSASCIIStringEncoding];
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
NSDictionary *myDictionary = [[unarchiver decodeObject] retain];
[unarchiver finishDecoding];
[unarchiver release];
My serialized NSDictionary looks like:
bplist00Ô01T$topX$objectsX$versionY$archiverÑR$0¯
!”#$%&'()U$nullÓ ZNS.objectsWNS.keysV$class¦
¦Tkey2Tkey5Tkey3Tkey1Tkey6Tkey4Wvalue 2o@
And it looks like I can’t convert this NSString to NSData and get my NSDictionary back.
NSData is NULL after the [dataUsingEncoding:dataUsingEncoding:NSASCIIStringEncoding].
Why on earth are you sending bytes as a
NSString– that’s never going to work!(a)
NSStringis for encoded textual data – i.e. data that follows a specific set of rules.(b)
NSDatais for a series of bytes that are just bytes.You have (b), not (a).
Send
NSDataobjects and don’t convert to/fromNSStringat all.EDIT what about URL paramters?
OK, so my answer above was a little too black and white.
If you really need to convert between data and string, take a look at base64 encoding – it will give you a safe string representation of your data at the expense of size.
There’s a few libraries outt here that can convert for you – try this one : https://github.com/nicklockwood/Base64
However, what will happen if you encode a dictionary on an iOS6 device and decode it on iOS5 – you can’t be 100% certain that will work. You might be better off writing your own coding/decoding methods that convert the dictionary to a string and back again. If it’s for a URL, why not just use URL parameters i.e.
x=5&name=Bob?