How to convert Base64 string to NSData?
Asked Answered
C

3

12

I have an iOS application (written in Swift) that retrieves data from a wcf service in JSON format. One of the data is an image stored as a base64string. However, I was not able to convert the base64string to NSData.

My main purpose is to convert base64string all the way to blob so that I could save that in the database. On the other hand, if you know at least part of it such as from base64string to NSData would be helpful.

Following code would give you the idea of my table

let ItemsDB = Table("Items")
let idDB = Expression<String>("ID")
let nameDB = Expression<String>("Name")
let catDB = Expression<String>("Category")
let uomDB = Expression<String>("UOM")
let priceDB = Expression<Double>("Price")
let imageDB = Expression<Blob>("Image")
let actDB = Expression<Bool>("Active")
Calen answered 11/2, 2016 at 14:40 Comment(2)
B64 to NSData: developer.apple.com/library/ios/documentation/Cocoa/Reference/…: (sorry for the previous erroneous links)Ovular
@EricD. Thanks, by any chance do you know how to convert NSData to blob?Calen
C
13

To convert from Base64 string to NSData

 let nsd: NSData = NSData(base64EncodedString: Image, options: NSDataBase64DecodingOptions.IgnoreUnknownCharacters)!

To Convert to Blob

nsd.datatypeValue
Cranberry answered 11/2, 2016 at 15:27 Comment(0)
S
11

This works:

Swift 3, 4 & 5:

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

Swift 2:

var data = NSData(base64EncodedString: recording_base64, options: NSDataBase64DecodingOptions.IgnoreUnknownCharacters)
Syne answered 3/5, 2019 at 7:59 Comment(1)
"Type of expression is ambiguous without more context" is the error I getAlarm
L
3

There are lot of example you can find online but most of them are in Objective-c. For example, Converting between NSData and base64 strings

It is pretty straight forward for you to use

NSData(base64EncodedString: String, options: NSDataBase64DecodingOptions)

Lerner answered 11/2, 2016 at 14:52 Comment(3)
By any chance do you know how to convert NSData to blob?Calen
Sry, I never done that before but as my search result shows, you can use yourNSData?.bytes as blob when you insert into DBLerner
Thanks but I found the answer... NSData.datatypeValueCalen

© 2022 - 2024 — McMap. All rights reserved.