Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
531 views
in Technique[技术] by (71.8m points)

base64 - How to convert a base64String to String in Swift?

I am receiving a base64String from webservice response in NSData, how to convert that base64String to String in swift?

    //Code
    var jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as! NSDictionary  // Response JSON from webservice
    var base64String : String = ""
    base64String = jsonResult["Base64String"] as! String  // Retrieve base64String as string from json response
    println("Base64String Alone: (base64String)")

// Code to decode that base64String
let decodedData = NSData(base64EncodedString: base64String, options: NSDataBase64DecodingOptions(rawValue: 0))
                                    println("Decoded:  (decodedData)")
                                    let decodedString = NSString(data: decodedData!, encoding: NSUTF8StringEncoding)
                                    println(decodedString) // Prints nil

Encode and decode of base64String works well for the files containing only text, if a file contains some table formats/images both encoding and decoding gives an invalid base64String. How to convert a file into base64String encode and decode whatever the contents of file ? File formats are doc, docx, pdf, txt

Advance thanks for any help !

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

try this

let base64Encoded = "YW55IGNhcm5hbCBwbGVhc3VyZS4="

let decodedData = Data(base64Encoded: base64Encoded)!
let decodedString = String(data: decodedData, encoding: .utf8)!

print(decodedString)

println(decodedString)

make sure your base 64 encoded string is valid


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...