user
user

Reputation: 71

how to make Transformable image in swift?

I am trying to make Transformable image in swift with core data. I create imageA that is Transformable. when I try to see is there image in database it tells that there is nothing there. how to add image to database ? what is wrong with my code? here is my code

I use methods setImage and getImage in place where saving and getting works for @NSManaged var isSet: NSNumber?

extension AppSettings {

    @NSManaged var isSet: NSNumber?
    @NSManaged var imageA: UIImage?

}

func setImage(inputAppSettings : AppSettings)
{
    let theImage = UIImage(named: "image.png")
    inputAppSettings.imageA = theImage
}



func getImage(inputAppSettings : AppSettings)
{
    if let theImage = inputAppSettings.imageA
    {
        print("theImage: \(theImage)")
    }
}

class MyTransformer:NSValueTransformer{

override class func allowsReverseTransformation() -> Bool
{
    return true
}


class func transformedValue(value:AnyObject) -> AnyObject
{
    var returnData:AnyObject = NSData()
    let theImage = value as! UIImage
    if let theData = UIImagePNGRepresentation(theImage)
        {returnData = theData}

    return returnData
}

class func reverseTransformedValue(value:AnyObject) -> AnyObject
{
    var returnImage:AnyObject = UIImage()
    let theData = value as! NSData
    if let theImage = UIImage(data: theData)
        {returnImage = theImage}

    return returnImage
}

override class func transformedValueClass() -> AnyClass
{
    return UIImage.self
}

}

func set()
{
    if let moc = self.managedObjectContext {
    let theAppSettingsAnyObject = NSEntityDescription.insertNewObjectForEntityForName("AppSettings", inManagedObjectContext: moc)
        if let theAppSettings = theAppSettingsAnyObject as? AppSettings
        {
            theAppSettings.isSet = true
            self.setImage(theAppSettings)
        }
        var savingError: NSError?
        do {
            try moc.save()
         } catch let error1 as NSError {
            savingError = error1
        if let error = savingError{
            print("Failed to save . Error = \(error)")
        }
    }

    }
}

Upvotes: 0

Views: 1509

Answers (2)

Tom Harrington
Tom Harrington

Reputation: 70976

You're using UIImage, which conforms to NSCoding. As a result, you do not need a custom value transformer, because UIImage already has that covered. All you need to do is:

  1. Declare the attribute to have type Transformable in the Core Data model editor
  2. Read and write UIImage to that attribute. Transformation to/from a binary form will be handled by UIImage.

Upvotes: 2

Hitendra Solanki
Hitendra Solanki

Reputation: 4941

To Store image in Database is heavy operation, it will take more time to encode and decode or in transformation.

Instead of transformation, try to save image in Document directory, and store its url in database.

Upvotes: 0

Related Questions