Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save monsoir/468662c784e15d788332b68e52e2b477 to your computer and use it in GitHub Desktop.

Select an option

Save monsoir/468662c784e15d788332b68e52e2b477 to your computer and use it in GitHub Desktop.
Sometimes, we will get this error:
> Error Domain=NSCocoaErrorDomain Code=3840 "Unable to convert data to string around character 28." UserInfo={NSDebugDescription=Unable to convert data to string around character 28.}
The reason that causes this error is that the encoding(GBK for example) of the response data is not compatible with the default encoding(UTF-8) of iOS.
To resolve this, we need to convert the encoding of response data to UTF-8.
Here is the inline method of converting the encoding to UTF-8:
```objc
static NSString *GBK2UTF8(NSData *data) {
NSStringEncoding enc =CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
NSString *gbkString = [[NSString alloc] initWithData:data encoding:enc];
return gbkString;
}
```
After define the inline method, go to the lines where response data transfer happens.
First, transfer the binary data to `NSString` with the inline method above:
```objc
NSString *dataString = GBK2UTF8(data); // data is the binary response data
```
Then, create a new data object using UTF-8 encoding with the dataString:
```objc
data = [dataString dataUsingEncoding:NSUTF8StringEncoding];
```
Finally, the encoding of the data turns to UTF-8.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment