- Разработка под tvOS: tips & tricks
- Изменилось взаимодействие между приложением и пользователем
- Домашний экран Apple TV теперь выглядит по-новому
- Добавление Top Shelf в tvOS application-проект
- Параллакс
- Два способа разработки: TVML vs нативное приложение
- Ограничения
- Авторизация
- Top shelf apple tv
- Providing Top Shelf Content
- Dynamic Content Layouts
- Carousel Actions
- Carousel Details
- Sectioned Content Row
- Play video from Apple TV Top Shelf
Разработка под tvOS: tips & tricks
Все знают, что еще в сентябре Apple представила Apple TV четвертого поколения с новой операционной системой tvOS на борту, и что для него можно разрабатывать свои приложения. О том, как это делать, уже кое-что писали, и в этой статье мы тоже обратимся к этой теме. О чем необходимо знать, приступая к разработке под tvOS и как избежать некоторых сложностей?
Изменилось взаимодействие между приложением и пользователем
Раньше мы могли прикоснуться к экрану, нажать на кнопку, перелистнуть картинку — работали с интерфейсом напрямую. Теперь взаимодействие происходит опосредованно, у пользователя есть два способа взаимодействия:
- Через пульт управления
- Управление при помощи Siri
Пульт управления тоже обновился, теперь там есть:
- Тач панель (можно тапать, свайпать и т.д.)
- Кнопка меню
- Siri
- Микрофон
- Play/Pause
- Домой
- Громкость
- Гироскоп
- Отверстие для зарядки
Также Пульт можно использовать как джойстик для игр. А еще Apple предоставила возможность подключать сторонние джойстики и написала инструкцию, как обеспечить работу своего джойстика.
Но что значит для команды разработки взаимодействие через пульт? Значит это то, что пользователю нужно давать понять, на каком элементе управления он находится и на что может нажать в каждый конкретный момент. Для это сделано такое средство как Focus. Focus говорит о том, что в одно и то же время в фокусе может находиться один и только один элемент.
UIKit framework поддерживает только интерфейсы, которые поддерживают работу с Focus. Другими словами, для большинства элементов Focus работает “из коробки”. Программно Focus можно только заставить обновиться, но установить или передвинуть его программно нельзя.
Что значит в большинстве случаев? Например, UIButton поддерживает фокус. На нее можно нажать.UILlabel Focus не поддерживает, на лейбл нельзя нажать — да и зачем? По умолчанию Focus поддерживают следующие UI-элементы:
- UIButton
- UITextField
- UITableView
- UICollectionView
- UITextView
- UISegmentedControl
- UISearchBar
Об обновлении Focus более подробно написано в документации.
Домашний экран Apple TV теперь выглядит по-новому
TOP SHELF
Теперь он состоит из иконок приложения и Top Shelf (опционально), который располагается над иконкой приложения. Когда пользователь выбирает ваше приложение (фокусируется ), над иконкой появляется Top Shelf.
Top Shelf – некое подобие виджета, если проводить паралели с iOS.
Top Shelf отличное место, чтобы продемонстрировать ключевой контент вашего приложения (например, погода) или сделать шорткат для пользователя, например, вернуть его к просмотру фильма, который поставлен на паузу.
Для вашего приложения Top Shelf является расширением (extension). Специально для работы с ним написан новый фреймворк – TV Services framework, который состоит из:
Объекта TVContentIdentifier – уникальный идентификатор медиаконтента
Объекта TVContentItem – любой из элементов или контейнер для элементов, отображаемых в Top Shelf
Протокола TVTopShelfProvider с двумя обязательными для реализации методами
topShelfItems – возвращает элементы, которые должны быть отображены в Top Shelf
topShelfStyle – говорит о том, какой стиль использовать для отображения элементов
Добавление Top Shelf в tvOS application-проект
Для того чтобы добавить Top Shelf в проект, необходимо:
- Добавить новый target в ваш проект.
File > New > Target - Выбирать TV Service Extention
tvOS > Application Extention > tvOS > Application Extention - Дать имя для вашего Top Shelf
- Согласиться активировать схему Top Shelf для отладки
- В проекте появится папка с вашим только что созданным Top Shelf
Ну а дальше дело техники — выбираем стиль отображения TopShelf и добавляем необходимые элементы. Варианты реализации можно посмотреть в примере проекта от Apple.
Параллакс
Иконка тоже не такая простая, как кажется. Все иконки в tvOS должны поддерживать параллакс.
Apple разработала для параллаксных картинок новый формат файла – .lsr
Параллакс достигается многоуровневым наложением картинок, такие картинки можно создавать либо прямо из Xcode, либо из специальной удобной программы Parallax Previewer, другой альтернативный вариант — скачать расширение для Photoshop. В архиве вместе с расширением для Photoshop есть инструкция по работе.
Два способа разработки: TVML vs нативное приложение
Каждый из них имеет свои преимущества и недостатки.
1. TVML
Первый способ предполагает использование стека технологий TVML, TVJS и TVMLKit
- TVML – Television Markup Language – родственник XML
- TVJS – набор JavaScript API, который обеспечит создание интерфейса приложения
- TVMLKit – клей между TVML, JavaScript и приложением для tvOS
И чтобы нам было проще, Apple подготовила для нас инструкции и каталог шаблонов,
Плюс: Приложение можно обновлять, обновляя свой сервер. Больше вам не придется ждать ревью в аппсторе!
Минус: Слабо кастомизируется. Нативные приложения всегда будут выглядеть лучше.
Вообще, это отличное решение типичного юскейса для приложения на Apple TV. Допустим, у вас уже есть сервер, который предоставляет видеоконтент для пользователей, и вы не хотите заморачиваться с дизайном или сложной навигацией для вашего tvOS-приложения. В таком случае разработка приложения с помощью TVML подойдет вам идеально.
2. Нативное приложение
В этом случае процесс разработки под Apple TV практически идентичен созданию обычных iOS-приложений, здесь также можно использовать Objective-С и/или Swift. Большинство iOS-фреймворков доступны и для tvOS, среди них MediaPlayer или UIKit. Полный список можно найти тут.
Ограничения
Нет локального хранилища данных. Для хранения приходится использовать iCloud, CloudKit или свой собственный бэкэнд.
Размер приложения не должен превышать 200 Мб.
Авторизация
Отдельно хотелось рассказать про проблемы с авторизацией. Сейчас ввод пароля выглядит примерно так:
Авторизация требуется довольно часто, например, при покупке фильма или загрузке приложения, даже бесплатного. Довольно скоро такой способ авторизации покажется утомительным. Поэтому если в вашем приложении присутствует авторизация, стоит задуматься о том, как сделать ее менее болезненной. В сети уже можно найти несколько примеров интересных решений (1, 2), но никто не запрещает пофантазировать дальше и попробовать использовать для авторизации QR-коды, Siri (“сим-сим-откройся”) или тач-панель пульта для ввода графического кода (как в Android).
Источник
Top shelf apple tv
The Apple TV Home screen uses the top shelf to showcase your content in a rich, engaging way while also giving people access to their favorite apps in the Dock. When you support fullscreen top shelf, people can swipe through multiple fullscreen content views, play trailers and previews, and get more information about your content.
Watch Spider-Man: Into the Spider-Verse Spider-Man: Into the Spider-Verse is available on the Apple TV app. Spider-Man: Into the Spider-Verse © 2018 Sony Pictures Animation Inc. All rights reserved. MARVEL and all related character names © & ™ 2019 MARVEL.
The top shelf is a unique opportunity for your app to highlight new, featured, or useful content and let people jump directly to it. For example, when people select Apple TV in the Dock, full-screen previews immediately begin playing and soon the Dock slides away. As people watch previews for the first show, they can swipe through previews of all other featured shows, stopping to select Play or More Info for a preview that interests them.
Providing Top Shelf Content
People use top shelf to discover new content, so it’s a great opportunity to showcase lively, engaging content that encourages people to dive into your app for more. Apple defines several layout templates you can use to give people a compelling top shelf experience when they select your app in the Dock.
Design a unique app icon that builds an emotional connection with people. An inviting, instantly recognizable app icon is essential, especially in the App Store, where people don’t yet have access to the dynamic, fullscreen previews you provide for top shelf. After people download your app, you want to make it easy for them to find and select your app icon and then become immersed in your top shelf content. For design guidance, see App Icon.
Help people jump right into playback. Top shelf provides a path to content that people care about most. The carousel layout templates both include two buttons by default: A primary button that should always begin playback and a More Info button that should open your app to a view that displays details about the content. For guidance, see Carousel Actions and Carousel Details.
Feature new content. For example, if you offer movies, showcase new releases; don’t promote movies that people have already purchased, rented, or watched. Similarly, if you offer episodic content, feature episode or season trailers, new shows, new seasons, and shows that are coming soon, and avoid promoting content people have already watched or purchased.
Personalize favorite content. People are familiar with apps they put in the top shelf of the Apple TV Home screen and use them often. You can personalize the experience by showing targeted recommendations in the top shelf, allowing people to resume media playback or jump back into active gameplay.
Avoid showing advertisements or prices. People put your app into top shelf because you’ve already sold them on it and they may not appreciate seeing lots of ads from your app. Showing purchasable content in the top shelf is fine, but put the focus on new and exciting content, and consider displaying prices only when people show interest.
Showcase compelling dynamic content. The videos and imagery you show in the top shelf should draw people in and make them crave more. If necessary, you can supply static images, but people typically prefer a captivating, dynamic top shelf experience that features the newest or highest rated content. (To learn how to create multilayer images, see Layered Images.)
Dynamic Content Layouts
Dynamic top shelf imagery can appear in several ways:
- A carousel of fullscreen video and imagery that includes two buttons and optional details
- A row of focusable content
- A set of scrolling banners
Regardless of the layout style you use, show content that people care about the most and help them get to it quickly.
For downloadable top shelf image templates that can help you position your content, see Resources.
Carousel Actions
The carousel actions layout style focuses on fullscreen video and imagery and includes a few unobtrusive controls that help people see more. This layout style works especially well to showcase content that people already know something about. For example, it’s great for displaying user-generated content, like photos, or new content from a franchise or show that people are likely to enjoy.
Watch Spider-Man: Into the Spider-Verse Spider-Man: Into the Spider-Verse is available on the Apple TV app. Spider-Man: Into the Spider-Verse © 2018 Sony Pictures Animation Inc. All rights reserved. MARVEL and all related character names © & ™ 2019 MARVEL.
Provide a title. Include a succinct title, like the title of the show or movie or the title of a photo album. If necessary, you can also provide a brief subtitle. For example, a subtitle for a photo album could be a range of dates; a subtitle for an episode could be the name of the show.
Carousel Details
This layout style extends the carousel actions layout style by giving you the opportunity to include some information about the content. For example, you might provide information like a plot summary, cast list, and other metadata that helps people decide whether to choose the content.
Provide a title that identifies the currently playing content. The content title appears near the top of the screen so it’s easy for people to read it at a glance. Above the title, you can also provide a succinct phrase or app attribution, like «Featured on My App«.
Sectioned Content Row
This layout style shows a single labeled row of sectioned content. It’s commonly used to highlight recently viewed content, new content, or favorites. Content in the row is focusable, which lets people scroll through it as fast as they want. A label appears when an individual piece of content comes into focus, and small movements on the remote’s touch surface bring the focused image to life. A sectioned content row can be configured to show multiple labels, if desired.
Provide enough content to constitute a complete row. At a minimum, load enough images in a sectioned content row to span the full width of the screen. In addition, include at least one label for greater platform consistency and to provide additional context.
The following image sizes are supported for a sectioned content row:
Источник
Play video from Apple TV Top Shelf
I have created a simple AppleTV project to display a number of videos by category, browsing and playing videos is working fine. It has been implemented as a client-server application using TVML and TVJS, so most of the application logic is in the Javascript files. These are statically generated in the background from dynamic content on a regular basis.
I’ve then added a TopShelf extension to the application which pulls in some featured videos from an API, this is also working fine, Pulls in the videos as expected.
The problem I am having is detecting and reacting to a user selecting a video from the top shelf. I have created a URL scheme exampletvapp:// which I have registered in my plist file.
I have also added the displayURL and playURL’s to the TVContentItems. When selecting one of the videos, my app is launched as expected but does not actually handle the playback of that video.
In my AppDelegate file I have added print statements to print the launchOptions and also added a openUrl function, which does get called but only logs this if I close the application and select something from the top shelf quickly before the app closes and I lose the debug session.
I have added a console.log to the JS file to check if the options are being passed over, but it’s not logging anything. my intentions here was to create a Player object with a playlist of just the selected video from the TopShelf. but as the URL only seems to pass the ID over, It would mean that I need to make an ajax request to get the video information even though I had it in the TVContentItem already.
So my question is: Am I supposed to natively add the video from topshelf into a playlist and play it (with Swift) or pass the details on to the javascript side for it to play it. If it’s the javascript is there a way to see the output from the console.log? As I dont see any which is making it quite difficult to work with.
UPDATE:
I’ve got a little further with this, I discovered (via the Apple Developer Forums) that you can attach Safari to the JS Context in the simulator for Apple TV via the Develop > Devices menu. I’ve done this and so far the URL is not being passed to the JS via the options. The url is passed to the openURL delegate function which needs to be either passed to the JS somehow or I need to natively play the video.
I’m currently investigating natively playing the video by passing all the required information in the displayURL to create a TVContentItem. I cannot see a way to pass this object to the JS from the openURL method unless I create a new context and instance of the controller (which may not even work)
Источник