Michael_mhr Michael_mhr - 7 months ago 58
Swift Question

Swift2 Convert String to NSData

I'm currently writing an App in Swift2 that communicates with a server (also written in Swift).
The problem is, is that the framework i use for the Tcp connection does only support to send Strings but I want to send a NSData to the client.

converting the NSData to String is very easy:

String(theData) // returns <62706c......0111 00000412>


but I don't know how to convert the String with the Data, that comes out of this function, back to NSData

Can somebody help me please?

Thanks in advance,
Michael

Answer

You need to encode the data using base64 encoding.

for example NSData -> String

let data = NSData()
let encodedBase64String = data.base64EncodedStringWithOptions([])

and decode it back String -> NSData

let decodedData = NSData(base64EncodedString: encodedBase64String, options: [])

You might pass appropriate encoding and decoding options if needed