Cross-Platform Images in Core Data

In an upcoming-release of iSMARTtrain, I’ve added a profile picture for the user settings. To support the iOS version of iSMARTtrain (coming soon), this needed to work cross-platform in a Core Data document.

Transferring images between the two platforms in a common format seems rather complicated, as there’s no common image format that can be easily extracted from both NSImage and UIImage. In the end, I ended up saving the images on the Mac side as PNG files, which can be handled natively by UIImage on the iOS side.

Self‘ in these cases is a Core Data NSManagedObject

On the Mac Side:

Save the image:

- (void)saveProfileImage:(NSImage *)profile {
      NSData *imageData = [profile TIFFRepresentation];
      NSBitmapImageRep *imageRep = [NSBitmapImageRep imageRepWithData:imageData];
      NSDictionary *imageProps = [NSDictionary dictionaryWithObject:[NSNumber numberWithFloat:1.0] forKey:NSImageCompressionFactor];
      NSData *imagePNGData = [imageRep representationUsingType:NSBitmapImageFileTypePNG properties:imageProps];
      self.image = imagePNGData;
  }

Retrieve the image

- (NSImage *)profileImage {
      if (self.image) {
            NSData *imageData = self.image;
           NSImage *newImage = [[NSImage alloc] initWithData:imageData];
           return newImage;
       }
       return nil;
 }

On the iOS Side:

Save the image:

- (void)saveProfileImage:(UIImage *)profile {
       self.image = UIImagePNGRepresentation(profile);
}

Retrieve the image:

- (UIImage *)profileImage {
      if (self.image) {
            NSData *imageData = self.image;
            UIImage *newImage = [[UIImage alloc] initWithData:imageData];
            return newImage;
      }
       return nil;
 }