Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert base64 into NSDATA in swift

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.

like image 251
Muhammad Zeshan Arif Avatar asked Dec 07 '22 21:12

Muhammad Zeshan Arif


1 Answers

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)
like image 122
Muhammad Zeshan Arif Avatar answered Dec 25 '22 17:12

Muhammad Zeshan Arif