11

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")
meda
  • 45,103
  • 14
  • 92
  • 122
  • B64 to NSData: https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSData_Class/index.html#//apple_ref/occ/instm/NSData/initWithBase64EncodedString:options: (sorry for the previous erroneous links) – Eric Aya Feb 11 '16 at 14:47
  • @EricD. Thanks, by any chance do you know how to convert NSData to blob? –  Feb 11 '16 at 14:58

3 Answers3

13

To convert from Base64 string to NSData

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

To Convert to Blob

nsd.datatypeValue
gayan1991
  • 753
  • 2
  • 11
  • 35
10

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)
skety777
  • 210
  • 2
  • 6
2

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)

Community
  • 1
  • 1
Breek
  • 1,431
  • 13
  • 24
  • 1
    By any chance do you know how to convert NSData to blob? –  Feb 11 '16 at 14:58
  • 1
    Sry, I never done that before but as my search result shows, you can use `yourNSData?.bytes` as blob when you insert into DB – Breek Feb 11 '16 at 15:08
  • Thanks but I found the answer... NSData.datatypeValue –  Feb 11 '16 at 15:24