SDK для интеграции плеера IVI в сторонние ios-приложения

Overview

IVIExternPlayerSDK

SDK позволяет интегрировать плеер IVI в сторонние приложения.

Требования

  • iOS 12.0 и выше
  • В Info.plist приложения должен быть выставлен флаг:
<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>

Установка

Swift Package Manager

Является предпочтительным способом установки SDK.

IVIExternPlayerSDK поддерживает подключение через Swift Package Manager.

Для того, чтобы подключить IVIExternPlayerSDK к своему проекту необходимо выбрать в Xcode пункт меню File -> Swift Packages -> Add Package Dependency...

Шаг 1

Ввести адрес GitHub-репозитория SDK - https://github.com/ivi-ru/ivi-extern-player-sdk-apple

Шаг 2

Выбрать необходимую версию SDK

Шаг 3

Добавить IVIExternPlayerSDK к таргету

Шаг 4

Ручная установка

Необходимо добавить в проект фреймворк IVIExternPlayerSDK.xcframework, а также фреймворки, которые используются как его зависимости:

  • IVIFoundation.xcframework
  • ProofOfWorkSwift.xcframework
  • IVIToss.xcframework
  • IVIFairPlay.xcframework
  • PopcornAV.xcframework
  • Popcorn.xcframework
  • Comet.xcframework

Для каждого из них должна быть выставлена настройка Emded & Sign в разделе Frameworks, Libraries, and Embedded Content вкладки General соответствующего таргета проекта:

Зависимости

Добавление бандла с ресурсами

Для разных партнёров в SDK могут использоваться разные заставки плеера. Необходимый бандл с ресурсами для заставки выдаётся менеджером IVI. Бандл должен быть добавлен в соответствующий таргет проекта. Он будет обнаружен SDK автоматически. SDK выкинет fatalError после своего запуска в случае отсутствия бандла.

Пример использования

import IVIExternPlayerSDK

class ViewController: UIViewController {
    
    private var player: IVIExternPlayer!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Данные для структуры `IVIAppInfo` уникальны для каждого приложения 
        // и выдаются менеджером IVI.
        let appInfo = IVIAppInfo(subsite: 123,
                                 appVersion: 12345,
                                 requestKeys: IVIAppInfo.RequestKeys(k: "qwerty123n",
                                                                     k1: "qwerty1n",
                                                                     k2: "qwerty2n"),
                                 app: nil)
                                 
        // Инициализируем плеер с конфигурационными данными.
        let configuration = IVIPlayerConfiguration(appInfo: appInfo,
                                                   userSession: "valid_ivi_user_session",
                                                   allowsAirPlay: true,
                                                   isNativeVolumeIndicationEnabled: false)
        player = IVIExternPlayer(configuration: configuration)
        
        // Подписываемся на события плеера.
        player.delegate = self

        // Добавляем view плеера в иерархию.
        self.view.addSubview(player.mediaView)
        player.mediaView.leftAnchor.constraint(equalTo: self.view.leftAnchor).isActive = true
        player.mediaView.rightAnchor.constraint(equalTo: self.view.rightAnchor).isActive = true
        player.mediaView.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true
        player.mediaView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true
        player.mediaView.translatesAutoresizingMaskIntoConstraints = false
        
        // Запускаем необходимый контент по его id на IVI.
        player.openContent(7029)
    }
}

События плеера приходят объекту, реализующему протокол IVIPlayerDelegate:

extension ViewController: IVIPlayerDelegate {
    func didChangeState(_ state: IVIPlayerState) {
        // Изменилось состояние плеера.
    }
            
    func didChangeCurrentTime(_ currentTime: Double) {
        // Изменилась текущая позиция воспроизведения видео.
    }
    
    func didChangeItemDuration(_ duration: Double) {
        // Обновилась длительность видеофайла.
    }
        
    func playbackDidReachEnd() {
        // Достигнут конец видеофайла.
    }
    
    func didChangeExternalPlaybackType(_ externalPlaybackType: IVIExternalPlaybackType) {
        // Изменился тип воспроизведения видео на внешние устройства.
    }
}

Плеер поддерживает смену качества, локализации и включение субтитров. Например, если пользователь выбрал первые доступные субтитры из списка доступных для текущего контента, сообщаем об этом плееру:

player.changeSubtitle(to: player.subtitles.first!)

Логирование

SDK умеет логировать свои события и отправлять логи на сервер IVI.

Выбор уровня логирования (по умолчанию равен .info):

IVILogger.shared.logLevel = .debug

Получение накопленного лога:

IVILogger.shared.log

Отправка накопленного лога на сервер IVI:

IVILogger.shared.send {
    // Лог отправлен
}
You might also like...
 VGPlayer - 📺  A simple iOS video player by Vein.
VGPlayer - 📺 A simple iOS video player by Vein.

Swift developed based on AVPlayer iOS player,support horizontal gestures Fast forward, pause, vertical gestures Support brightness and volume adjustment, support full screen, adaptive screen rotation direction.

Open Source iOS 360 Degree Panorama Video Player.
Open Source iOS 360 Degree Panorama Video Player.

🎺 🎺 🎺 🎺 🎺 🎺 🎺 🎺 🎺 🎺 🎺 The Metal with Swift 5.0 version is comming 🎺 🎺 🎺 🎺 🎺 🎺 🎺 🎺 🎺 🎺 🎺 360 VR Player A Open Source, Ad-free, Na

Lightweight YouTube Downloader for iOS
Lightweight YouTube Downloader for iOS

DownTube DownTube is a very lightweight app that allows you to download any YouTube video for offline use. Note: this app goes against YouTube's TOS a

📱iOS app to extract full-resolution video frames as images.
📱iOS app to extract full-resolution video frames as images.

Frame Grabber is a focused, easy-to-use iOS app to extract full-resolution video frames as images. Perfect to capture and share your favorite video mo

FWVideoPlayer is video Player for iOS in Swift.

FWVideoPlayer Desc FWVideoPlayer is video Player for iOS in Swift. It can play video and audio. You can use it easy. Example To run the example projec

iOS video player for trailer. You can customize layout for the control panel. Support PiP and DRM.

iOS video player for trailer. You can customize layout for the control panel. Support PiP and DRM.

iOS platform video hard decoding, support h264, h265

VideoDecoder iOS platform video hard decoding, support h264, h265 Example To run the example project, clone the repo, and run pod install from the Exa

A simple iOS app similar to iTunes where you can view details of your favorite movies, songs and audio books.
A simple iOS app similar to iTunes where you can view details of your favorite movies, songs and audio books.

Popcorn Adventure This is an iOS app developed by Arthur Tristan M. Ramos who has taken the Appetiser iOS Coding Challenge. Design Pattern The design

Gumlet analytics integration with AVPlayer for iOS native applications.

gumlet-Insights-avplayer Gumlet Insights integration with AVPlayer for iOS native applications. This Insights enables you to get useful data about vid

Owner
ivi
ivi
Support customization of any player SDK and control layer

Support customization of any player SDK and control layer

紫枫 6.9k Dec 30, 2022
Official SwiftUI SDK for Stream Chat.

SwiftUI - Currently in Development ?? The SwiftUI SDK is built on top of the StreamChat framework and it's a SwiftUI alternative to the StreamChatUI S

Stream 136 Dec 23, 2022
High-quality Interactive Audio/Video Unity SDK

简体中文 | English TRTC Unity SDK Overview Leveraging Tencent's many years of experience in network and audio/video technologies, Tencent Real-Time Commun

LiteAVSDK 8 Dec 23, 2022
Collection of Swift/iOS-related conference videos. A demo project for SuperArc framework - building modular iOS apps with a µComponent architecture.

SwiftCommunity Beta version is available at TestFlight Collection of Swift/iOS-related conference videos. This project serves as a showcase for the Su

SuperArcSwift 52 Dec 2, 2022
Camera and Microphone streaming library via RTMP, HLS for iOS, macOS, tvOS.

HaishinKit (formerly lf) Camera and Microphone streaming library via RTMP, HLS for iOS, macOS, tvOS. Issuesの言語は、日本語が分かる方は日本語でお願いします! Sponsored with ??

shogo4405 2.4k Dec 29, 2022
BMPlayer - A video player for iOS, based on AVPlayer, support the horizontal, vertical screen

A video player for iOS, based on AVPlayer, support the horizontal, vertical screen. support adjust volume, brightness and seek by slide, support subtitles.

Eliyar Eziz 1.8k Jan 4, 2023
MobilePlayer - A powerful and completely customizable media player for iOS

MobilePlayer A powerful and completely customizable media player for iOS. Table of Contents Features Installation Usage Customization Skinning Showing

Sahin Boydas 3k Jan 2, 2023
NextLevelSessionExporter is an export and transcode media library for iOS written in Swift.

NextLevelSessionExporter ?? NextLevelSessionExporter is an export and transcode media library for iOS written in Swift. The library provides customiza

NextLevel 233 Nov 27, 2022
▶️ video player in Swift, simple way to play and stream media on iOS/tvOS

Player Player is a simple iOS video player library written in Swift. Looking for an obj-c video player? Check out PBJVideoPlayer (obj-c). Looking for

patrick piemonte 2k Jan 2, 2023
Swifty360Player - iOS 360-degree video player streaming from an AVPlayer.

Swifty360Player iOS 360-degree video player streaming from an AVPlayer. Demo Requirements Swifty360Player Version Minimum iOS Target Swift Version 0.2

Abdullah Selek 148 Dec 18, 2022