我想将字符串转换为Base64.我在几个地方找到了答案,但它在Swift中不再起作用了.我正在使用Xcode 6.2.我相信答案可能适用于以前的Xcode版本,而不是Xcode 6.2.
有人可以指导我在Xcode 6.2中这样做吗?
我找到的答案是这个,但它在我的Xcode版本中不起作用:
var str = "iOS Developer Tips encoded in Base64"
println("Original: \(str)")
// UTF 8 str from original
// NSData! type returned (optional)
let utf8str = str.dataUsingEncoding(NSUTF8StringEncoding)
// Base64 encode UTF 8 string
// fromRaw(0) is equivalent to objc 'base64EncodedStringWithOptions:0'
// Notice the unwrapping given the NSData! optional
// NSString! returned (optional)
let base64Encoded = utf8str.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.fromRaw(0)!)
println("Encoded: \(base64Encoded)")
// Base64 Decode (go back the other way)
// Notice the unwrapping given the NSString! optional
// …Run Code Online (Sandbox Code Playgroud) 我有以下base64编码的字符串:
eyJhbGciOiJSUzI1NiIsImtpZCI6IjdEODU3RjE3RjMwQTBBNzY4OUQ4RTFDMTI0RjRFMzk1MEU2REIyQ0YiLCJ0eXAiOiJKV1QiLCJ4NXQiOiJmWVZfRl9NS0NuYUoyT0hCSlBUamxRNXRzczgifQ
Run Code Online (Sandbox Code Playgroud)
我可以轻松地在线解码,例如这里
但是,当我尝试快速解码时,我不成功,我使用了:
func fromBase64() -> String? {
guard let data = Data(base64Encoded: self) else {
return nil
}
return String(data: data, encoding: .utf8)
}
Run Code Online (Sandbox Code Playgroud)
但是我返回零。