How to convert base64 into NSDATA in swift
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)
How to convert Base64 string to NSData?
To convert from Base64 string to NSData
let nsd: NSData = NSData(base64EncodedString: Image, options: NSDataBase64DecodingOptions.IgnoreUnknownCharacters)!
To Convert to Blob
nsd.datatypeValue
Converting between NSData and base64 strings
Scroll down to the Conclusion section on the page you linked and download the provided NSData+Base64 files. Its the best solution I have seen so far and is incredibly easy to use. If you can learn anything about Cocoa, you can learn to use that project.
Example
NSString *originalString = [NSString stringWithFormat:@"test"];
NSData *data = [NSData dataFromBase64String:originalString];
NSLog([data base64EncodedString]);
The above will print out the original string after converting it to base64 and back to a normal unencoded string.
How to convert a base64String to String in Swift?
Try this:
let base64Encoded = "YW55IGNhcm5hbCBwbGVhc3VyZS4="
var decodedString = ""
if let decodedData = Data(base64Encoded: base64Encoded) {
decodedString = String(data: decodedData, encoding: .utf8)!
}
if !decodedString.isEmpty {
print(decodedString)
} else {
print("Oops, invalid input format!")
}
Make sure your base 64 encoded string is valid.
WARNING (edit)
In most base64
decoding implementations like Java
, the padding-character is not needed, but Data(base64Encoded:)
returns nil
if it's missing.
Swift 5 solution; use String.fromBase64(_:)
instead, after implementing like:
extension Data {
/// Same as ``Data(base64Encoded:)``, but adds padding automatically
/// (if missing, instead of returning `nil`).
public static func fromBase64(_ encoded: String) -> Data? {
// Prefixes padding-character(s) (if needed).
var encoded = encoded;
let remainder = encoded.count % 4
if remainder > 0 {
encoded = encoded.padding(
toLength: encoded.count + 4 - remainder,
withPad: "=", startingAt: 0);
}
// Finally, decode.
return Data(base64Encoded: encoded);
}
}
extension String {
public static func fromBase64(_ encoded: String) -> String? {
if let data = Data.fromBase64(encoded) {
return String(data: data, encoding: .utf8)
}
return nil;
}
}
As mentioned on editor's profile,
above edit's code allows Apache 2.0 license as well,
without attribution need.
swift:How to save the base64String encoded Image into local directory
You can save image in local directory in following way. Add Image extension with fileName
.
let filePath = "\(NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0])/\(fileName)"
let imageData : Data = UIImagePNGRepresentation(image)! as Data
imageData.write(toFile: filePath, atomically: true)
Convert base 64 string into image return nil in swift
The problem is that the string you pass to Data(base64Encoded:
is not actually base64encoded, it contains some more plaintext in the front.
You need to remove that and only pass the actual base64 encoded image, like so:
let str = "/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAMCAgICAgMCAgIDAwMDBAYEBAQEBAgGBgUGCQgKCgkICQkKDA8MCgsOCwkJDRENDg8QEBEQCgwSExIQ..."
let dataDecoded : Data = Data(base64Encoded: str)!
let decodedimage = UIImage.init(data: dataDecoded)
Alternatively you can programatically split the original data at the ,
and take the second part as the actual data input.
At that point you can remove the options: .ignoreUnknownCharacters
as well since now there should not be any non-base64 chars left - and if there are you should fix the data instead of the code.
Final note: depending on where you get the data from it might be a good idea to not force-unwrap anything and instead deal with a broken / missing image by e.g. displaying a placeholder image.
Related Topics
Pure Swiftui Login, Signup, Register Flow, Is It Possible
Longer Subtitles in Mapview Annotations (Swift)
Drag Uibutton Without It Shifting to Center [Swift 3]
How to Convert a Persian Date into a Gregorian in Swift
Swiftui Present View Modally via Tabview
Swift:Background Color Fading Animation (Spritekit)
How to Add Two or More Buttons to Annotationview: Mkannotationview
iOS - Setobject VS. Synchronize
Nsfetchedresultscontroller Swift Sections
Nsexceptionallowsinsecurehttploads Not Working for Ip Addresses
Please Add the Host Targets for the Embedded Targets to the Podfile
Displaying Strings in iOS Randomly Without Repeating Them
Updating Label Takes Too Long (Swift)