我试图用Swift编码和解码字符串和数据。
在Java中它相对简单,我可以使用Charset
CharsetDecoder
CharsetEncoder
,如下面的代码段所示。
我认为解决方案是使用String.Encoding
但是如何使用?
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);
while(newByteBuff.hasRemaining()){
char ch = (char) newByteBuff.get();
System.out.print(ch);
}
newByteBuff.clear();
}
答案 0 :(得分:0)
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)")
}
}
答案 1 :(得分:0)
Swift3回答
let str = "iOS Developer Tips encoded in Base64"
print("Original: \(str)")
let utf8str = str.data(using: String.Encoding.utf8)
if let base64Encoded = utf8str?.base64EncodedString(options:Data.Base64EncodingOptions(rawValue: UInt(0)))
{
print("Encoded: \(base64Encoded)")
if let base64Decoded = NSData(base64Encoded: base64Encoded, options:NSData.Base64DecodingOptions(rawValue: UInt(1)))
.map({ NSString(data: $0 as Data, encoding: String.Encoding.utf8.rawValue) })
{
// Convert back to a string
print("Decoded: \(base64Decoded)")
}
}