1

On the process of trying Firebase, as a possible replacement to Parse.com (unfortunately to disappear), I have saved a PNG image online using the code below, in Swift.

    let fn = self.toolBox.getDocumentsDirectory().stringByAppendingPathComponent("M0-1.png")
    let im = UIImage(contentsOfFile: fn),
    dat = UIImagePNGRepresentation(im!),
    b64 = dat?.base64EncodedStringWithOptions(.Encoding64CharacterLineLength),
    qs = ["string": b64!],
    r = diltRootRef.childByAppendingPath("zs"),
    us = ["img": qs]
    r.setValue(us)

The saving part seems to work, but how am I suppose to get back the image I saved? All I have tried so far failed.

David East
  • 31,526
  • 6
  • 67
  • 82
Michel
  • 10,303
  • 17
  • 82
  • 179

1 Answers1

1

I would recommend retrieving images using observeSingleEventOfType(:_), because it's a one-time read.

Once you have the string value synchronized, you can use an NSData() initializer, and then create an UIImage.

imageRef.observeSingleEventOfType(.Value) { (imageSnap: FDataSnapshot!) in
  let base64String = imageSnap.value as! String
  let decodedData = NSData(base64EncodedString: base64String, options: NSDataBase64DecodingOptions(rawValue: 0))    
  let image = UIImage(data: decodedData!)
}

Check out this example repo on using base64 images in a UITableView.

David East
  • 31,526
  • 6
  • 67
  • 82
  • 1
    There is both read and write swift code in the answer to this question [Swift2 retrieving images from Firebase](http://stackoverflow.com/questions/33644560/swift2-retrieving-images-from-firebase/34044446#34044446) and with David's answer change the read from observeEventType to observeSingleEventOfType – Jay Feb 06 '16 at 16:01
  • @Jay please mark this question as a duplicate. – Frank van Puffelen Feb 06 '16 at 16:02
  • @FrankvanPuffelen done – Jay Feb 06 '16 at 16:05
  • See the duplicate question: it works. This snippet of code produces an error for me. – thiagowfx May 03 '16 at 04:27
  • What's the error @thiagowfx? The other question uses a realtime observer which is not great for performance when downloading images. – David East May 03 '16 at 04:43