1

I am using below code to convert an image to Data so that I can send it to my watch extension using watchSession.updateApplicationContext.

UIGraphicsBeginImageContextWithOptions(localQrView.subviews[0].bounds.size, false, 1.0)
localQrView.subviews[0].layer.render(in: UIGraphicsGetCurrentContext()!)
let viewImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
let imageData = viewImage.pngData()

Now the problem is when I execute this code for the first time and see the imageData.count, it returns only 560 bytes of data. That means, on the watch extension I am not receiving the right data of the image. From the second time, it gives 14240 bytes which then converts to image normally on the watch extension.

Can anyone see if something is being done wrong here?

PS: For watch extension, I can't send an Image (UIImage) directly hence I adopted to the conversion on the app from image to data, and from data to image on the watch extension.

Daniel
  • 3,188
  • 14
  • 34
Lohith Korupolu
  • 1,066
  • 1
  • 18
  • 52
  • 2
    If you try to render those 560 bytes, do you get any image that makes sense? Could it be that `localQrView.subviews[0]` changes from something like an all white view to your actual QR code? Maybe the size changes? Could you try printing stuff out and see if anything changes between the first and second time? – Daniel Aug 19 '19 at 15:25
  • @Daniel... I see some hints from your answer. The UIView is duties from a framework and I think it returns a white block first. The 560 bytes doesn't render anything except a white blank block – Lohith Korupolu Aug 19 '19 at 20:57
  • What calls this function? Could it be the QR code isn't rendered the first time it's called? Also, I'm pretty sure you can just render the localQrView (ie you don't need to go down through its subviews) using [`drawHierarchy(...)`](https://developer.apple.com/documentation/uikit/uiview/1622589-drawhierarchy) – Daniel Aug 19 '19 at 21:45
  • the localQrView also has other UI elements in it (two UILabels). So, to get only the image, I am going down through its subviews. – Lohith Korupolu Aug 20 '19 at 08:04

0 Answers0