6

I am working on an iOS project. It stores audio on web server in the form of base64 string. When I request server to get base64 Strings for all audios and tried convert it in NSData I am getting nil.

do
{
   var audioData: NSData! = NSData(base64EncodedString: audioBase64String, options: NSDataBase64DecodingOptions(rawValue:0))
   if audioData != nil
   {
      let sound = try AVAudioPlayer(data: audioData)
      sound.play()
   }
   else
   {
        print("Data Not Exist")
   }
}
catch
{
}

On Android same base64 string is converted into byte array and is playing, but in iOS audioBase64String return nil for NSData.

Ichigo Kurosaki
  • 3,765
  • 8
  • 41
  • 56
  • Include a sample base64 in your question. Is it possible that adding `NSDataBase64DecodingIgnoreUnknownCharacters` already fixes the issue? (maybe you b64 ends in a newline?) – hnh Aug 29 '16 at 12:21
  • You already getting Base 64 String from server and you again doing same thing for encoding thats why you not getting result. So need to do decode now. – Anand Nimje Aug 29 '16 at 12:30
  • thanks @hnh Solved – Muhammad Zeshan Arif Aug 29 '16 at 12:58

3 Answers3

16

This works:

Swift 3 and 4:

var audioData = Data(base64Encoded: recording_base64, options: .ignoreUnknownCharacters)

Swift 2:

var audioData = NSData(base64EncodedString: recording_base64, options: NSDataBase64DecodingOptions.IgnoreUnknownCharacters)
3

For Swift 3:

var audioData = Data(base64Encoded: recording_base64, options: .ignoreUnknownCharacters)
pableiros
  • 14,932
  • 12
  • 99
  • 105
-2

Try this library. You can get NSData from base64 string and then init your AVAudioPlayer with this data. Please read AVAudioPlayer Apple's Documentation.

Serhii Londar
  • 231
  • 1
  • 18