Search code examples
iosswiftbase64line-breaks

Swift won't recognize /n line breaks after base64 string decoding


I am trying to take my base64 decoded string and print it, but the result does not recognize the line breaks. For example,

print("Hi \n hello \n hi")

Print like this

Hi
hello
hi

As expected, but when I decode the encoded version of the string, and print the result, it returns the string without the line breaks recognized. Here is my code.

var encodedString = "SGkgXG4gaGVsbG8gXG4gaGk="

let decodedData = NSData(base64EncodedString: encodedString, options: NSDataBase64DecodingOptions.IgnoreUnknownCharacters),
        decodedString = NSString(data: decodedData!, encoding: NSUTF8StringEncoding)

print (decodedString!)
 // prints "Hi \n hello \n hi"

How do I change my code to allow Swift to recognize these line breaks? Thanks!


Solution

  • Your string is not encoded properly, I have checked your string encodedString in playground when you decode it decodedString contain string like this way Hi \\n hello \\n hi, it is escaping the \n thats why it is printing \n with output. Try to encode properly string like this way.

    var str = "Hi \n hello \n hi"
    let utf8str = str.dataUsingEncoding(NSUTF8StringEncoding)
    if let base64Encoded = utf8str?.base64EncodedStringWithOptions([])
    {
        let decodedData = NSData(base64EncodedString: base64Encoded, options: []),
        decodedString = NSString(data: decodedData!, encoding: NSUTF8StringEncoding)
        print (decodedString!)
    }
    

    Edit: The problem is here is string is encode in PHP and you are decoding in the app with swift. Your decoding string contain \\n instead of \n means it is escaping the \n character one way to solve is replace \\n with \n but it is not preferable but right not it will work for you like this way.

    var str = decodedString!.stringByReplacingOccurrencesOfString("\\n", withString: "\n")
    print (str)
    

    Note: It is batter if you encode/decode both on the same side means either on your PHP or the application side with swift.