scinfu scinfu - 1 year ago 350
Swift Question

Swift decode and encode string

I'm trying to encode and decode strings and data with Swift.
In Java it's relatively simple , i can use

like in the below snippet code .
I think the solution is to use
but how?

public static void Test() throws CharacterCodingException {
Charset charset = Charset.forName("UTF-8");
CharsetDecoder chdecoder = charset.newDecoder();
CharsetEncoder chencoder = charset.newEncoder();
String s = "Encode and Decode Example.";
if(!chencoder.canEncode((char) 9)) return;//not here but i need this method
ByteBuffer byteBuffer= ByteBuffer.wrap(s.getBytes());
CharBuffer charBuffer = chdecoder.decode(byteBuffer);
ByteBuffer newByteBuff = chencoder.encode(charBuffer);
char ch = (char) newByteBuff.get();

Answer Source
let str = "iOS Developer Tips encoded in Base64"
println("Original: \(str)")
let utf8str = str.dataUsingEncoding(NSUTF8StringEncoding)
if let base64Encoded =      utf8str?.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0)) 
println("Encoded:  \(base64Encoded)")
if let base64Decoded = NSData(base64EncodedString: base64Encoded, options:   NSDataBase64DecodingOptions(rawValue: 0))
                      .map({ NSString(data: $0, encoding: NSUTF8StringEncoding) })
    // Convert back to a string
    println("Decoded:  \(base64Decoded)")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download