简体   繁体   中英

Which encoding should I use to convert NSData to NSString and backwards, if the string doesn't need to be beautiful?

Cheers,

my app needs to send the contents of a NSData object to a webserver as a parameter of a GET request. It should be able to receive that very same data back at a later time. The data will be stored as longtext in a mysql database, the content is not known to me and may be pretty much anything.

To achieve this, I'll need to convert it into a NSString, but which encoding should I choose? Does it matter at all which one I choose as long as it is the same for both ways?

Thanks!!

If you really need to convert your data to a string, use a Unicode encoding, as unicode provide a codepoint for every possible character. The most common unicode encoding is obviously UTF-8 ( NSUTF8StringEncoding )

But if this is arbitrary data that you need to transfer, and that data does not represent a string, don't convert it into a string, whatever the encoding . It will leads to problems (eg if your data contains a zero byte, it will be considered as a string terminator, etc.)

Instead, if you need to transfer some raw data to your server, consider:

  • Using POST instead of GET if possible
  • Encode your data in Base64 , so that you ensure you won't loose any data when converting nor during your transport from your client to your server (or worse, corrupt your data by converting to an arbitrary encoding)
  • If possible on your server (if it is yours and you have access to the code), decode your Base64-encoded string back to raw data upon reception, and store it in a BLOB field instead of in a VARCHAR or BIGTEXT field.
  • If you can't access the server code, and have no choice of storing it in a TEXT/VARCHAR field in your db, you can still store the Base64-encoded string representing your data directly in your database (and decode it when you retrieve it from the DB later).

See Google for Base64 encoding in Objective-C, there are plenty of references to a widely used NSString+Base64 category.

You should use Base -64 encoding for this. See this answer for details/code:

How do I do base64 encoding on iphone-sdk?

The parameters of the GET requests should be strings, and in an ideal (most-compatible) world they're fully escaped 7-bit ASCII. Taking arbitrary data and encoding it one of the traditional Unicode string encodings in order to put it into a URL will cause you all sorts of pain and mystery bugs.

Base-64 is designed for data <=> string encoding. (Versus string <=> string encoding.)

As long as you use the same kind of encoding, you should be good. For most purposes, UTF-8 is good. NSUTF8StringEncoding

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM