I have that code
func SendRequest(request: String) -> String
{
var response = \"\"
var (success, errmsg) = client.connect(timeout: 1)
if succe
Answering: "Sometimes, cast NSData to String doesn't work."
Not all data is convertible to a particular string encoding. In the case:
var str = String.init(data: bytes, encoding: NSUTF8StringEncoding)
there are a great number of bytes and byte sequences that have no valid UTF-8 character encoding.
Note: I don't speak Swift. This following code may not compile, but it should give you the main idea/logic behind it.
The issue was because there NSData
was incomplete (you receive them piece by piece and the buffer size may not be sufficient to handle the complete response at once), assuming that the bytes are really transformable to NSString
according to the encoding used, as @zaph pointed out.
Simple example: Transform a UIImage
into NSData
using UIImageJPEGRepresentation()
for example, and try to transform it into NSString
using the wanted encoding, it may not be valid, or do the same with the stream of a video.
An example for our case:
Full valid "Character": "1001", nothing with "10" nor "01".
You receive "10" only. And if you convert it to NSString
, it's nil because it's not valid.
Then, you receive "01". And if you convert it to NSString
, it's nil because it's not valid.
So you have to read all the NSData
before transforming it to NSString
.
So at the beginning, you can create a var finalData = NSMutableData.init()
Then, each time you read the buffer, do:
var partialData = NSData.init(bytes: data, length: data.count)
finalData.appendData(partialData)
At the end, just transform finalData
to String
:
if let str = String(data:finalData, encoding: NSUTF8StringEncoding) {
response = str
}
Some possibilities to examine include whether or not data actually contains any bytes, and whether or not it's actually a valid UTF-8 string. Assuming this is an http request/response that you're handling, check the Content-type
, in particular the charset
property. If the data's encoded as something other than text , or it's not UTF-8 format, it won't convert to a string.