title: Swift 3 - Saving images to Core Data
body: <p>For some reason I can't figure out how to save images to core data and fetch them again. I have a feeling it's something about my types but have a look:</p>
  
  <p><a href="https://i.stack.imgur.com/ef0KX.png" rel="noreferrer"><img src="https://i.stack.imgur.com/ef0KX.png" alt="Image is saved as Binary Data and stored in External Record File"></a></p>
  
  <p>I get my data from an api call to my server. It returns a base64 string. 
  Here is where I get the data:</p>
  
  <pre><code>updateAccessTokenOnly(newAccessToken: aToken!)
  saveImageToDB(brandName: imageBrandName, image: data! )
  </code></pre>
  
  <p>Here I save it to my DB:</p>
  
  <pre><code>func saveImageToDB(brandName: String, image: Data) {
      dropImages(){tableDropped in
          let managedContext = getContext()
          let entity = NSEntityDescription.entity(forEntityName: "CoffeeShopImage", in: managedContext)!
          let CSI = NSManagedObject(entity: entity, insertInto: managedContext)
  
          CSI.setValue(image, forKey: "image")
          CSI.setValue(brandName, forKey: "brandName")
  
          do {
              try managedContext.save()
              print("saved!")
          } catch let error as NSError {
              print("Could not save. \(error), \(error.userInfo)")
          }
      }
  }
  </code></pre>
  
  <p>then to fetch it:</p>
  
  <pre><code>    func getImageFromDB(callback: @escaping (_ image: UIImage)-&gt; ()) {
  
      let fetchRequest: NSFetchRequest&lt;NSManagedObject&gt; = NSFetchRequest(entityName: "CoffeeShopImage")
  
      do {
          let searchResults = try getContext().fetch(fetchRequest)
  
          for images in searchResults {
              print("vi når her ned i get image")
              if (images.value(forKey: "brandName")! as! String == "Baresso"){
                  print(images.value(forKey: "brandName")! as! String)
  
                  let image: Data = images.value(forKey: "image")! as! Data
                  let decodedimage = UIImage(data: image)
  
                  callback(decodedimage!)
  
              }
          }
      } catch {
          print("Error with request: \(error)")
      }
  }
  </code></pre>
  
  <p>Full error log:</p>
  
  <p><a href="https://docs.google.com/document/d/1gSXE64Sxtzo81eBSjv4bnBjBnnmG4MX2tuvNtnuJDIM/edit?usp=sharinghttp://" rel="noreferrer">https://docs.google.com/document/d/1gSXE64Sxtzo81eBSjv4bnBjBnnmG4MX2tuvNtnuJDIM/edit?usp=sharing</a></p>
  
  <p>Hope someone can help. Thanks in advance!</p>
  
  <p><strong>UPDATED</strong></p>
  
  <p>So I uninstalled the app and then the code above worked. However the pictures come out blue? (yes I've checked that the pictures sent from the database are correct).</p>
  
  <p>Any solution?</p>
  
  <p><a href="https://i.stack.imgur.com/WksbA.png" rel="noreferrer"><img src="https://i.stack.imgur.com/WksbA.png" alt="Pictures fetched from CoreData"></a></p>