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.
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)
For Swift 3:
var audioData = Data(base64Encoded: recording_base64, options: .ignoreUnknownCharacters)
Try this library. You can get NSData from base64 string and then init your AVAudioPlayer with this data. Please read AVAudioPlayer Apple's Documentation.
Related
I'm trying to send image to server via JSON string. Problem is the server didn't see my image in PNG or JPG format. Here is code how i do it:
enter image description here
That how i convert parameters to JSON string
enter image description here
What i want - it's encode UIImage to base64 string and send to server.
Thank You!
try using the below code and check if any error occurs or image value is nil
if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
if let imageData = UIImageJPEGRepresentation(image, 0.5) {
let base64String = imageData.base64EncodedString(options: Data.Base64EncodingOptions.init(rawValue: 0))
let dict: [String: Any] = ["data": base64String]
do {
let data = try JSONSerialization.data(withJSONObject: dict, options: .prettyPrinted)
if let string = String(data: data, encoding: .utf8) {
socket.write(string)
}
} catch {
print(error.localizedDescription)
}
}
}
This is how I create Data from UIImage:
let data = UIImagePNGRepresentation(image)
And then I need to convert it to String;
if let data = data {
let stringFromData = String(data: data, encoding: .utf8)
}
but stringFromData is nil. Why?
You can get it using the Data method base64EncodedString()
if let data = data {
let stringFromData = data.base64EncodedString()
// to decode base 64 string you can use Data base64Encoded String initializer
if let dataFromBase64 = Data(base64Encoded: stringFromData) {
print(data)
}
}
Convert Your image data in Base64 string
For Encode
let stringFromData : Data = Data(base64Encoded: strBase64, options: .ignoreUnknownCharacters)!
And decode
let strBase64 = imageData.base64EncodedStringWithOptions(.allZeros)
When I get my JSON back from my API this is how it looks
{
data:[
100,
80,
105,
99,
etc
]
}
How do I take this array and turn it back into a base64 string, then NSData and finally UIImage.
Here is what I have thus far.
let byteArray = todo["image"]["data"].arrayObject
var data = NSData(bytes: byteArray!, length: byteArray!.count)
var image = UIImage(data: data)
When printing the data it prints fine but returns nil for image.
Have you tried iterating throug the array and building a string from its elements, the use base64 encoding/decoding api to get back from string to NSData? Something like that(I'm writing from iPad so I can't check).
var encodedString=""
for smallString in byteArray {
encodedString += String(smallString)
}
let data = NSData(base64EncodedString: base64Encoded, options: NSDataBase64DecodingOptions.IgnoreUnknownCharacters)
var image = UIImage(data: data)
let byteArray = todo["image"]["data"].arrayObject
let string = String(bytes: byteArray, encoding: .utf8)
let encodedImageData = string
let imageData = NSData(base64Encoded: encodedImageData!)
let image = UIImage(data: imageData! as Data)
I'm kinda new to swift and i need some help with encoding some image, putting it in a JSON and after retrieving it, decoding it back to NSData and recreating the image in an UIImage view controller.
I've found this post Convert Image to Base64 string in iOS + Swift but i get stuck with this part:
let decodedData = NSData(base64EncodedString: base64String, options: NSDataBase64DecodingOptions.fromRaw(0)!)
because the fromRaw method is not available anymore.
Thanks in advance
Later edit:
I'm using swiftyJson to parse the array and i'm getting the image data like this:
var base64String = arrayJson[0]["photo"].stringValue
var imageString = base64String as NSString
and after that i'm trying to decode it like this:
let decodedData = NSData(base64EncodedString: imageString, options: NSDataBase64DecodingOptions.IgnoreUnknownCharacters)
I've also tried with the rawValue instead of IgnoreUnknownCharacters. Both return nil. Also tried with the base64String instead of imageString. Same thing.
You can do the following instead to make a base64 encoded string to an UIImage:
//base64 string to NSData
let decodedData = NSData(base64EncodedString: base64String, options: NSDataBase64DecodingOptions(rawValue: 0))
//NSData to UIImage
var decodedIamge = UIImage(data: decodedData!)
NSDataBase64EncodingOptions.fromRaw(0)! now is changed to NSDataBase64DecodingOptions(rawValue: 0)
For more encode/decode details, you can visit this post: Convert between UIImage and Base64 string
To encode an image:
let image = UIImage(...)
let quality = 1.0
let data: NSData = UIImageJPEGRepresentation(image, quality)!
To decode an image:
let decodedImage = UIImage(data: data)
The reason why these methods return nil for you could be that your base64string is an URL and Filename safe variant, meaning character 62 (0x3E) is replaced with a "-" (minus sign) and character 63 (0x3F) is replaced with a "_" (underscore) as noted here base64 alphabet
Try replacing character _ with / and character - with + in your string.
You could use the following code:
base64string = base64string.stringByReplacingOccurrencesOfString("-", withString: "+", options: NSStringCompareOptions.LiteralSearch, range: nil)
base64string = base64string.stringByReplacingOccurrencesOfString( "_" , withString: "/", options: NSStringCompareOptions.LiteralSearch, range: nil)
Also be aware of the correct length of the string. it has to be a multiple of 4
- take a look at this answer padded string.
NSData Class Reference : https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSData_Class/index.html#//apple_ref/c/tdef/NSDataBase64DecodingOptions
NSDataBase64DecodingOptions :
struct NSDataBase64DecodingOptions : RawOptionSetType {
init(_ rawValue: UInt)
init(rawValue rawValue: UInt)
static var IgnoreUnknownCharacters: NSDataBase64DecodingOptions { get }
}
Have you tried one of the followings :
let decodedData = NSData(base64EncodedString: base64String, options: NSDataBase64DecodingOptions(rawValue: 0)!)
let decodedData = NSData(base64EncodedString: base64String, options: NSDataBase64DecodingOptions.IgnoreUnknownCharacters)
How can I serialize JSON in swift? I am trying to serialize using this method, however it is causing EXC_BAD_INSTRUCTION. For downloading JSON data, I am using NSURLConnection.
var sJson : NSDictionary = NSJSONSerialization.JSONObjectWithData(nsMutData, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
How can I solve it?
Regards
Your root-level data is an array of dictionaries -- not a dictionary; therefore replace your line with:
var sJson = NSJSONSerialization.JSONObjectWithData(nsMutData, options: .MutableContainers, error: nil) as NSArray
I tested it and it now works with your data.
Here's how I tested it after having created a "json.txt" file in my project:
var filePath = NSBundle.mainBundle().pathForResource("json", ofType:"txt")
var nsMutData = NSData(contentsOfFile:filePath)
var sJson = NSJSONSerialization.JSONObjectWithData(nsMutData, options: .MutableContainers, error: nil) as NSArray
This is the swift 2.0 way
let path : String = NSBundle.mainBundle().pathForResource("jsonDict", ofType: "JSON")!;
let data : NSData = NSData(contentsOfFile: path)!;
var jsonDictionary : NSDictionary
do {
jsonDictionary = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions()) as! NSDictionary
} catch {
print(error)
}
In Swift 4+, JSON Serialization is best done by utilizing the Decodable and Encodable protocols.
Apple docs about encoding/decoding (or serializing/deserializing)
custom types
Download sample code from Apple on this page
There is also a detailed tutorial by Ray Wenderlich: Encoding and Decoding in Swift