2

I am trying to convert WKImage to Data(NSData) but always getting nil.

let image = WKImage(imageName: "sample")
print("Image = \(image)")

let imageData = image.imageData
print("Image Data = \(imageData)")

Below is out put

Image = <WKImage: 0x7a66ff40>
Image Data = nil
Anand Suthar
  • 3,678
  • 2
  • 30
  • 52
  • 2
    have a look here : https://developer.apple.com/reference/watchkit/wkimage/1628152-imagedata – DeyaEldeen Nov 25 '16 at 10:23
  • @DeyaEldeen Then how can one convert image to data(NSData) or this is not possible on watchOS ? – Anand Suthar Nov 25 '16 at 10:24
  • this might be useful, read it : http://stackoverflow.com/questions/37984502/wkimage-always-return-nil – DeyaEldeen Nov 25 '16 at 10:27
  • You can see in log I am getting image properly but when get it's imageData will return nil. I think it's not possible on watchOS – Anand Suthar Nov 25 '16 at 10:28
  • the last thing I can help with is, have a look at this code : https://github.com/mkoehnke/WKImageCache/blob/master/WKImageCache/WKImageCache.swift – DeyaEldeen Nov 25 '16 at 10:40
  • @AnandSuthar The important part on DeyaEldeen comment is the discussion on it: `The value in this property is set using the init(imageData:) method. For image objects created using other methods, this property is nil`. So that's normal behavior. – Larme Nov 25 '16 at 15:09

1 Answers1

0

If you are creating WKImage with init(imageName: String) constructor, only imageName parameter will not be nil. image and imageData parameters are not nil only when WKImage was created via init(image: UIImage) or init(imageData: Data) respectfully.

You can get this imageName, then create UIImage with it's init(named: String) constructor, and then convert this UIImage to data using UIImageJPEGRepresentation or UIImagePNGRepresentation functions:

UIImagePNGRepresentation(UIImage(named: image.imageName!)!)
abjurato
  • 1,439
  • 11
  • 17