How to convert base64 into NSDATA in swift

2020-04-14 03:37发布

问题:

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.

回答1:

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)


回答2:

For Swift 3:

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


回答3:

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