I am attempting to send a JSON representation of an object in an email link. The recipient will open the link and my app will respond via a url scheme. It must extract the JSON from the url and re-build the object.
I am serializing my object by building an NSDictionary and using:
return [NSJSONSerialization dataWithJSONObject:dictionary options:NSJSONWritingPrettyPrinted error:&error];
I’m not sure what comes next. Somehow I need to convert this NSData into a string so that I can prefix my url scheme and use it in a link.
On the receiving end, I then need to remove the prefix (which I can do) and turn the string back into an NSData.
What is the correct method for doing this? And how do I make sure that the contents of my data do not interfere with the JSON string encoding (e.g. if my object contains text including special characters)?
You need to do an additional encoding step, since there are characters in encoded JSON that also have significance when they are part of a URL. What we actually want to do is URL-encode the data so none of the characters in the resulting string conflict with what applications expect a URL to look like.
The first step is transforming our data into an
NSString(this is basically just a memcpy sinceNSStringsare encoded in UTF-8 by default):Now, there’s a function you might be tempted to use called
-stringByAddingPercentEscapesUsingEncoding, but it doesn’t do a thorough enough job of escaping all the relevant characters, so we need to build our own.I could repeat the code here, but since it’s been done many times already, just view this blog that shows how you can add a category to
NSStringto do proper encoding, after which you can append it and send it on its way. Writing the analogous decoding function withCFURLCreateStringByReplacingPercentEscapesUsingEncodingis an exercise for the reader of which many examples can be found floating around.Make sure your payloads are quite small (on the order of a couple of kB), by the way, since there is probably an upper bound on how long URLs, even those used locally and with a custom scheme, can be.