tvOS: edit TVContentItem images before the Top Shelf get presented

Apple TV

A few months ago I answered this question from Taimur Ajmal on StackOverflow. Taimur needed to locally resize the images presented in the Top Shelf Extension of his tvOS app.

As he pointed out, TVContentItem has an imageURL property, that is of NSURL type, but there isn’t any kind of UIImage-related property.

In these cases you need to find a workaround in order to achieve the result asked by Taimur. I thought: since imageURL is an URL, I could download it locally, modify the downloaded image with tools (like Core Graphics or other libraries) and present it. And it works like a charm!

So, these are the steps I followed:

  • grabbing the UIImage from internet
  • creating a new image context with the size of the top shelf image
  • saving it into the NSCacheDirectory
  • setting the local image URL as imageURL.

Let’s go!

  1. Let’s create our TVContentItem object:
  2. Set the contentItem‘s imageShape:
  3. Grab the image from Internet. Actually I did this synchronously, you can also try to use other async methods to get that (NSURLConnection, Alamofire, etc…):
  4. Prepare the path where your image will be saved and get your UIImage from the dataobject:
  5. Assuming you’ve already set the topShelfStyle property, get the size of the top shelf image with the method TVTopShelfImageSizeForShape. This will be the size of your image context:
  6. Create your image context of shapeSize size and draw the downloaded image into the context rect. Here you can do all your modifications to the image to adjust it into the desired size. In this example I took a square image from Instagram and I put white letterbox bands on the right and left sides.
  7. In the end, save this image into your NSCacheDirectory and set the image path as contentItem‘s imageURL.
  8. Complete your TVContentItem with other details (like title, internal link, etc…), run the top shelf extension… et voilà!

fsz5w

📝 License: CC BY-SA 3.0 with attribution required. Link to this post.
📷 Article: © Apple (source: apple.com). Screenshots: self-made

 

Nicola Giancecchi

Born in '93 in a tiny state lost in the middle of the italian peninsula (hint: it's not the Vatican City). Great computer science enthusiast and Apple fan, I love to write code in Swift, but I also like to work with other languages and environments (PHP, Android, Windows, etc). Three times Apple WWDC Scholarship Recipient. Coding since 2008, developing iOS apps since 2012.

 

Leave a Reply

Your email address will not be published. Required fields are marked *