I try to get an NSString from NSData but I get a nil value.
This is my code:
NSString *dataString = [[NSString alloc] initWithData:self.message.data encoding:NSUTF8StringEncoding];
When I log self.message.data I get:
Printing description of self->_message->_data:
<OS_dispatch_data: data[0x17e48290] = { leaf, size = 331233, buf = 0x3aac000 }>
That means my data is not nil…
Can anyone help?
As answer to your question in comments:
OS_dispatch_data is dispatch_data_t which has toll-free bridging with NSData on iOS 7 and Mavericks. You can simply cast it to NSData *.
So, in your case you can write:
NSData *dataCast = self.message.data;
NSString *dataString = [[NSString alloc] initWithData:dataCast encoding:NSUTF8StringEncoding];
And now you get the correct string!
In my case it appeared, when AFNetworking cast internal NSMutableData to NSData.
And this simple cast helps me.
UPD: As #Daij-Djan mentioned: If it's not works - try to check your text encoding.
For example if you're yousing NSURLSessionTask:
NSURLSessionTask *task; // Your NSURLSessionTask
NSString *encoding = [[task response] textEncodingName];
In your case (NSUTF8StringEncoding) it should be "utf-8".
Try UTF-16 encoding instead. It may be an error converting to UTF-8 if any data in there is not recognized.
Related
I know, JSON parsing questions are asked over and over again, but still I can't find any answer to this one.
I've been trying to read and parse a textual JSON file using NSJSONSerialization to no avail.
I've tried using the same JSON data from a NSString and it did work.
Here's the code:
NSError *error;
NSString *jsonString1 = [NSString stringWithContentsOfFile:jsonFilePath
encoding:NSUTF8StringEncoding
error:&error];
NSData *jsonData1 = [jsonString1 dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *jsonObject1 = [NSJSONSerialization JSONObjectWithData:jsonData1
options:0
error:&error];
NSString *jsonString2 = #"{\"key\":\"value\"}";
NSData *jsonData2 = [jsonString2 dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *jsonObject2 = [NSJSONSerialization JSONObjectWithData:jsonData2
options:0
error:&error];
- The text file contains one line: {"key":"value"}
- jsonString1 = #"{"key":"value"}"
- jsonString2 = #"{\"key\":\"value\"}"
- jsonData1 is 23 bytes in size
- jsonData2 is 15 bytes in size
- jsonObject1 is nil and I get error code 3840
- jsonObject2 is a valid dictionary
Seems like the problem is with reading the file, since the NSStrings and NSDatas differ, but what am I doing wrong here and how can I fix it?
Most likely you file contains some unprintable characters (e.g. \0) that trigger the failure. Printing the error message will tell you at what position the first invalid characters occurs.
For example, try printing "{\"key\":\u{0000}\"value\"}" and you'll seem to get a valid JSON, however decoding it fails.
I always do a check on the return value when doing anything with NSUTF8StringEncoding and if nil, then try NSASCIIStringEncoding:
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
if (jsonString == nil) {
jsonString = [[NSString alloc] initWithData:jsonData encoding:NSASCIIStringEncoding];
}
return jsonString;
I am receiving a warning in Xcode after upgrading to Xcode 7 in my project, I'm using CoacoSecurity which uses Base64 for encryption in the following line of code :
if (![NSData instancesRespondToSelector:#selector(initWithBase64EncodedString:options:)])
{
decoded = [[self alloc] initWithBase64Encoding:[string stringByReplacingOccurrencesOfString:#"[^A-Za-z0-9+/=]" withString:#"" options:NSRegularExpressionSearch range:NSMakeRange(0, [string length])]];
}
Its telling me that initWithBase64Encoding is deprecated, so how can i get over this warning and fix it.
I've converted it but I'm getting another warning:
decoded = [[self alloc] initWithBase64EncodedString:[string stringByReplacingOccurrencesOfString:#"[^A-Za-z0-9+/=]" withString:#""] options:NSRegularExpressionSearch];
The warning says:
Implicit conversion from enumeration type enum NSStringCompareOptions to different enumeration type NSDataBase64DecodingOptions (aka enum NSDataBase64DecodingOptions)
use this
NSData *decodedData = [[NSData alloc] initWithBase64EncodedString:base64String options:0];
instand of
NSData *data=[[NSData alloc]initWithBase64Encoding:(NSString *)dict];
Here's a solution that works with OSX 10.8 and up.
// assume sData is an NSString that's already been set
NSData *vData;
if ([vData respondsToSelector:#selector(base64EncodedStringWithOptions:)]) {
vData = [[NSData alloc] initWithBase64EncodedString:sData options:kNilOptions];
} else { // 10.8 or earlier
vData = [[NSData alloc] initWithBase64Encoding:sData];
}
NSString *sResult = [[NSString alloc]
initWithData:vData encoding:NSUTF8StringEncoding];
I threw in the sResult line only if you wanted to convert it to an NSString instead of an NSData.
So, that gives you a Base64 encoded string. If you want to now unencode it, you would do:
// assuming sData is an NSString that's already been set
NSString *sResult = #"";
NSData *vData = [sData dataUsingEncoding:NSUTF8StringEncoding];
if ([vData respondsToSelector:#selector(base64EncodedStringWithOptions:)]) {
sResult = [vData base64EncodedStringWithOptions:kNilOptions];
} else { // 10.8 or earlier
sResult = [vData base64Encoding];
}
Well, first i used initWithBase64Encoding as #Ske57 recommended and then to get over that warning i had to cast it to NSDataBase64DecodingOptions and it should work fine :
decoded = [[self alloc] initWithBase64EncodedString:[string stringByReplacingOccurrencesOfString:#"[^A-Za-z0-9+/=]" withString:#""] options:(NSDataBase64DecodingOptions)NSRegularExpressionSearch];
I have been trying to add sqlite3_column_blob type of value to NSString by this lines of code :
NSUInteger len = sqlite3_column_bytes(compiledStatement, n);
NSData *cData = [[NSData alloc] initWithBytes:sqlite3_column_blob(compiledStatement, n) length:len];
NSString *columnText = [NSString stringWithUTF8String:[cData bytes]];
Here is the BLOB data which i am trying to retrieve from the database :
�PNG
IHDRXXq�04sBIT|d�
�IDATx��{pEǿ� !�f��E���0��#����Q'p#iQ��È�L�P���R`6 F�COJD�q��0 ��\�FbrȁR�������c6��������f�����M��-����n"�~;�p0s��bɶX,c�U^7!�Q!��e�n�2��o�%��#���~3G!�^�X,��<�b��B\S�)ˬ`��Ť*S��#�.�9+c�8ADtN�fd�}����D4��̊�X����u9��f�y̜/_�c�
"J�D�V0�^"�0��h6��Du��,3s83���f"z��j���6M]!V�[q���\��+��O�QUU�K�.*~:���#HH�|�]�F�#tt�'�C�$wU�+<ט�� >}���`��rR�b<�sv��\��'Nb�8~�$��F��h����<z$��1�U{�J�t#'9��~e��X|*�b�I��]��+�:|F��B��6$IB��~xd��>aa����$�/�j��f�H��
rV����ز{>��ju1�Q��'�E�+}Q�/^��&����r�۰Ǿ>����A�:g�S��(��r}Q�Of���
��t��omƶw5Y7�-�$aꔉH�5]��>KD�}1�J`f0#7!DM`7u=p�0Vg��ҥ_��&%,�2^L�#Æ��ʘ�CI�*�8HD���-03�oko��7n"7�mߥ�ѷ���'b��9v:r='���z�������V^ͅ_���E�%z����bU�rt���|"z����y���ݴ��+0��y+.�`��P^^ᬈ�ow�n����S�� %5���[O�t�W������3yB�:]3s["�L;u��g4z�O��uH[�� 2=.�=ƣ>��;x��gA1+/�#JjZ�W����u&DG�����l%�jw�p)03��h�:���/�����^���"<�nl|#O����[$I��jdᮋ��%�7����ŋ���4�eܸq�!O�f���ݙ+;h%��o�z�зOO�I�1����`��g��*�yȫg���pd�x�v]__�=��Ǟ��4?^�()-Gn�,yA�(���wo��A���G��D��Sv&&No'.,9�����J����/�ۥL�0��L����s�m߅ke�4ڻ��.j6�aUV�ΦݢW�D�V!$$D3?$$��L�̞�j6���6H�=��L�u�Vy-r֚��z�7u�K۱K�����u6z���Ꙉ��?�Jpp̚��{�M����Xn�hŸ��x�71k�Sn�8!!!����M����
oۥ�5R�9�`�NB��D4˚VRZ��3��m����<���Ǿ>�s�.�����g#d���о���A��ᴨ�����t������
$I���ۙ:��-I�^$"������<�����_X�G��jL���Vy%ns��C�$!絕��+D�X�Zm�E0sof���E�%-N\���/ߴ
=t�w�h��(�3odf;+���Tc���j#���������Sv�n�]hb����nVRUU�lx�I��x��3=�#�Fc(Lٙ���=��[�N��-
m� ,O��V$?��غ'�#oͪ����5�<Y�O?s0
�WO��i�l���
p|\l��k�*r|\�G����v�j�Ǐ���l~
ߝ�5~q[Q|\,^�{-�ŵb4�����<����nBD�d�6������h��9���J��b�o
�7W����8���b�}�y�,03G1s!T.���O�|�U�����h~``4�"�侻(<~R�4���9
�B,`�T__���2�n���.k��Zi߾V������攨 R���E8�7~8W�r�p��M,{e�W�[?�Ѭ� fs�~�ë����R�l�����L���$i=T�_+�6��K0w�R]bm�`rr�y\�W���%��\���zd����$IkY`"�ff�9�?���!zD}�m�JN�:�l�z��b����:�(B����.x0<�RT\���]��m�.d����MEV�Z�"��uX�(]�Z+I����_�n�TQS����>ۙ��w~��Z��Y��;?qH���ù"]����fذ�"�9SY��o�{�h��}�'X��OP��:+�Ndo��b�L�^=Iv=}#��еk�|�l(E�Wq����Ů�v7J\#S�pf~���3?�̛�%���ѫʬ<y?��+Z���Q�����:�3�i���zB�/҈h���̊7�J��� �Z/� �:'�������)�u"z����Z����rЪ���$��։F%e(K�� �XSӾ��=��2�����`;��=�w7}�Z�Zٴ� ,��sb�}+�t����Z��u�AD)�B�{�[q�Z+"J�ƫ�ڃ����V9��
��
!�~�":�Kx�k��'8��3����`I�V�ۛk0�{S�G���Z�q���6{p%8�,�4�o�42���i>IDC��P�"����FC1���^ڊ���(/ˈh�rs�ڳ���[�{$&�kW���t�a��2��DtEY��+FDq��?�m�U�%��F����c���06ƍMnM8a�X��Q��6��������}�1��־X�����>�ѭ�(j�5m�3�;l���q��s�J"���R��9��C�|��#f�Z.Uf"J%"���#D�(���U��I�����&��9��Ҙ�]"�!���BD5AAAO3�m�=6&�&��*~G1i�x���AAAO����f��$I�)����4�X�$,��̴KSk��ݿy;g����a�"�A�Z<K���&u2ҝ���Q����u6-�<����p�,�����V���s�E�kQ��Dc�¹β55��I#�MD�:���)��ZD�W��uB��5�6f�*I�W9<
)`3?�c�R�RfK�Cʨaf�����盓���8åx ���L���,%� N�k�#D�̼[�ֿ_�Yݢ<��֬v0�3�n���tO�$Ir�ڷOO�7��1rXX'�7�o��yZ����}5���Dc�y=���78�v�o�����c���������A��}�Up�b"����A�a~�(!D=���_��\\���a�m��:��%�&̼S��b��]�f#3��Jd��
6���<u�D�I���^&�����b\94L�/�j� �E�%شy���d�a�1}�����$�����ڋ8p�0�-l�c�I���ô�L���c�A%����tE1���wv�m>�d�|P�5T-��~{P�3,�j�X-�����QY�3��+PU]�˗�#JJ�����DC��бct��#��(DFޏ=Z�b悠���:j�r��R��aQ1Ζy|I��b�~o/)���g�h�R�!r��XN'���C\����DtV��M>����Z�9�G����L!D�Ƒ�
�%S.��GN�
�CSW4����vhj�v�!P���?� �kɲIEND�B`�
But every time i am getting nil response although there is a value exist. Rest of the parameter values are coming just i am getting nil response in above value.
Thanks.
The reason you cannot convert that data to a string is because it's a PNG image file:
�PNG
(I assume; I haven't looked at the PNG spec to confirm this, it's just an assumption at this stage).
Finally i got the solution for the above issue which i was facing :
NSData *content = [[NSData alloc] initWithBytes:sqlite3_column_blob(compiledStatement, 2) length:sqlite3_column_bytes(compiledStatement, 2)];
NSString *columnText = [content base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
I'm trying to encrypt/decrypt an NSString and return the original string in the end. Here's how I convert the string to a data object:
NSData *string_data = [string dataUsingEncoding:NSUTF8StringEncoding];
And after that data has been encrypted/decrypted I want it back to the original string by doing:
NSString *to_string = [NSString stringWithCString:[decrypted_data bytes] encoding:NSUTF8StringEncoding];
The encoding seems to match, but I still get a null when I try to print out to_string to the console. I've tried all sorts of encoding settings. It doesn't seem to work.
Use:
NSString *to_string = [[NSString alloc] initWithData:string_data encoding:NSUTF8StringEncoding];
It is not safe to use stringWithCString because the bytes buffer you get from NSData is not guaranteed to be null-terminated.
Currently I am download data from a server and I have this line to get that NSData into a NSString.
NSString *txt = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
How would I go from here to convert that NSString into a UTF8 string?
Thanks!
NSData *utf8Data = [txt dataUsingEncoding:NSUTF8StringEncoding];
Change NSASCIIStringEncoding to NSUTF8StringEncoding .
I ran a quick test now with some dummy data and seemed to work fine with just that one line.