diff --git a/Objective-C/BasicExample/app/ViewController.m b/Objective-C/BasicExample/app/ViewController.m index eaa6768..3f9e4f3 100644 --- a/Objective-C/BasicExample/app/ViewController.m +++ b/Objective-C/BasicExample/app/ViewController.m @@ -5,6 +5,26 @@ @import GoogleInteractiveMediaAds; // [START_EXCLUDE] +typedef NS_ENUM(NSInteger, StreamType) { + /// Live stream. + StreamTypeLive, + /// VOD. + StreamTypeVOD, +}; + +/// Specifies the ad pod stream type; either `StreamTypeLive` or `StreamTypeVOD`. +/// +/// Change to `StreamTypeVOD` to make a VOD request. +static StreamType const kStreamType = StreamTypeLive; +/// Live stream asset key. +static NSString *const kLiveStreamAssetKey = @"c-rArva4ShKVIAkNfy6HUQ"; +/// VOD content source ID. +static NSString *const kVODContentSourceID = @"2548831"; +/// VOD video ID. +static NSString *const kVODVideoID = @"tears-of-steel"; +/// Network code. +static NSString *const kNetworkCode = @"21775744923"; + /// The backup stream is only played when an error is detected during the stream creation. static NSString *const kBackupContentUrl = @"http://devimages.apple.com/iphone/samples/bipbop/bipbopall.m3u8"; @@ -77,20 +97,18 @@ - (void)requestStream { // Create a stream request. Use one of "Live stream request" or "VOD request", depending on your // type of stream. IMAStreamRequest *request; - // Switch this variable to NO to make a VOD request. - BOOL useLiveStream = YES; - if (useLiveStream) { + if (kStreamType == StreamTypeLive) { // Live stream request. Replace the asset key with your value. - request = [[IMALiveStreamRequest alloc] initWithAssetKey:@"c-rArva4ShKVIAkNfy6HUQ" - networkCode:@"21775744923" + request = [[IMALiveStreamRequest alloc] initWithAssetKey:kLiveStreamAssetKey + networkCode:kNetworkCode adDisplayContainer:self.adDisplayContainer videoDisplay:self.imaVideoDisplay userContext:nil]; } else { // VOD request. Replace the content source ID and video ID with your values. - request = [[IMAVODStreamRequest alloc] initWithContentSourceID:@"2548831" - videoID:@"tears-of-steel" - networkCode:@"21775744923" + request = [[IMAVODStreamRequest alloc] initWithContentSourceID:kVODContentSourceID + videoID:kVODVideoID + networkCode:kNetworkCode adDisplayContainer:self.adDisplayContainer videoDisplay:self.imaVideoDisplay userContext:nil]; diff --git a/Objective-C/PodServingExample/app/ViewController.m b/Objective-C/PodServingExample/app/ViewController.m index c529032..823562b 100644 --- a/Objective-C/PodServingExample/app/ViewController.m +++ b/Objective-C/PodServingExample/app/ViewController.m @@ -1,59 +1,63 @@ -// Copyright 2024 Google LLC. All rights reserved. -// -// -// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this -// file except in compliance with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software distributed under -// the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF -// ANY KIND, either express or implied. See the License for the specific language governing -// permissions and limitations under the License. - #import "ViewController.h" - #import +// [START import_ima_sdk] @import GoogleInteractiveMediaAds; -typedef enum {liveStream, vodStream} streamType; -/// Specifies the ad pod stream type; either `liveStream` or `vodStream`. -static streamType const kRequestType = liveStream; +// [START_EXCLUDE] +typedef NS_ENUM(NSInteger, StreamType) { + /// Live stream. + StreamTypeLive, + /// VOD. + StreamTypeVOD, +}; + +/// Specifies the ad pod stream type; either `StreamTypeLive` or `StreamTypeVOD`. +/// +/// Change to `StreamTypeVOD` to make a VOD request. +static StreamType const kStreamType = StreamTypeLive; /// Google Ad Manager network code. -static NSString *const kNetworkCode = @""; +static NSString *const kNetworkCode = @"YOUR_NETWORK_CODE"; /// Livestream custom asset key. -static NSString *const kCustomAssetKey = @""; +static NSString *const kCustomAssetKey = @"YOUR_CUSTOM_ASSET_KEY"; +// [START custom_vtp_handler] +/// Custom VTP Handler. +/// /// Returns the stream manifest URL from the video technical partner or manifest manipulator. -static NSString *(^gCustomVTPParser)(NSString *) = ^(NSString *streamID) { +static NSString *(^gCustomVTPHandler)(NSString *) = ^(NSString *streamID) { // Insert synchronous code here to retrieve a stream manifest URL from your video tech partner // or manifest manipulation server. - NSString *manifestUrl = @""; - return manifestUrl; + // This example uses a hardcoded URL template, containing a placeholder for the stream + // ID and replaces the placeholder with the stream ID. + NSString *manifestUrl = @"YOUR_MANIFEST_URL_TEMPLATE"; + return [manifestUrl stringByReplacingOccurrencesOfString:@"[[STREAMID]]" + withString:streamID]; }; - -/// Fallback URL in case something goes wrong in loading the stream. If all goes well, this will not -/// be used. -static NSString *const kBackupStreamURLString = @""; +// [END custom_vtp_handler] +/// The backup stream is only played when an error is detected during the stream creation. +static NSString *const kBackupContentUrl = + @"http://devimages.apple.com/iphone/samples/bipbop/bipbopall.m3u8"; +// [END_EXCLUDE] @interface ViewController () +/// The entry point for the IMA DAI SDK to make DAI stream requests. +@property(nonatomic, strong) IMAAdsLoader *adsLoader; +/// The container where the SDK renders each ad's user interface elements and companion slots. +@property(nonatomic, strong) IMAAdDisplayContainer *adDisplayContainer; +/// The reference of your video player for the IMA DAI SDK to monitor playback and handle timed +/// metadata. +@property(nonatomic, strong) IMAAVPlayerVideoDisplay *imaVideoDisplay; +/// References the stream manager from the IMA DAI SDK after successful stream loading. +@property(nonatomic, strong) IMAStreamManager *streamManager; -/// Content video player. -@property(nonatomic, strong) AVPlayer *contentPlayer; - -// UI +// [START_EXCLUDE] /// Play button. @property(nonatomic, weak) IBOutlet UIButton *playButton; -/// UIView in which we will render our AVPlayer for content. +/// UIView for the video player. @property(nonatomic, weak) IBOutlet UIView *videoView; - -// SDK -/// Entry point for the SDK. Used to make ad requests. -@property(nonatomic, strong) IMAAdsLoader *adsLoader; -/// Main point of interaction with the SDK. Created by the SDK as the result of an ad request. -@property(nonatomic, strong) IMAStreamManager *streamManager; -/// Video display used by the SDK to play ads. -@property(nonatomic, strong) id videoDisplay; +/// Video player to play the DAI stream for both content and ads. +@property(nonatomic, strong) AVPlayer *videoPlayer; +// [END_EXCLUDE] @end @@ -62,51 +66,47 @@ @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; + // [START_EXCLUDE] self.playButton.layer.zPosition = MAXFLOAT; - [self setupAdsLoader]; - [self setUpContentPlayer]; -} - -- (IBAction)onPlayButtonTouch:(id)sender { - [self requestStream]; - self.playButton.hidden = YES; -} - -#pragma mark Content Player Setup - -- (void)setUpContentPlayer { - // Load AVPlayer with path to our content. - NSURL *contentURL = [NSURL URLWithString:kBackupStreamURLString]; - self.contentPlayer = [AVPlayer playerWithURL:contentURL]; + // Load AVPlayer with path to your content. + NSURL *contentURL = [NSURL URLWithString:kBackupContentUrl]; + self.videoPlayer = [AVPlayer playerWithURL:contentURL]; // Create a player layer for the player. - AVPlayerLayer *playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.contentPlayer]; + AVPlayerLayer *playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.videoPlayer]; // Size, position, and display the AVPlayer. playerLayer.frame = self.videoView.layer.bounds; [self.videoView.layer addSublayer:playerLayer]; -} + // [END_EXCLUDE] -#pragma mark SDK Setup - -- (void)setupAdsLoader { self.adsLoader = [[IMAAdsLoader alloc] initWithSettings:nil]; self.adsLoader.delegate = self; -} -- (void)requestStream { - // Create an ad display container for ad rendering. - IMAAdDisplayContainer *adDisplayContainer = + // Create an ad display container for rendering each ad's user interface elements and companion + // slots. + self.adDisplayContainer = [[IMAAdDisplayContainer alloc] initWithAdContainer:self.videoView viewController:self companionSlots:nil]; + // Create an IMAAVPlayerVideoDisplay to give the SDK access to your video player. - self.videoDisplay = - [[IMAAVPlayerVideoDisplay alloc] initWithAVPlayer:self.contentPlayer]; + self.imaVideoDisplay = [[IMAAVPlayerVideoDisplay alloc] initWithAVPlayer:self.videoPlayer]; +} +// [END import_ima_sdk] + +// [START make_stream_request] +- (IBAction)onPlayButtonTouch:(id)sender { + [self requestStream]; + self.playButton.hidden = YES; +} + +- (void)requestStream { + // Create a stream request. IMAStreamRequest *request; - if (kRequestType == liveStream) { - // Create a pod serving request for a livestream. + if (kStreamType == StreamTypeLive) { + // Live stream request. Replace the network code and custom asset key with your values. request = [[IMAPodStreamRequest alloc] initWithNetworkCode:kNetworkCode customAssetKey:kCustomAssetKey adDisplayContainer:adDisplayContainer @@ -114,8 +114,8 @@ - (void)requestStream { pictureInPictureProxy:nil userContext:nil]; } else { - // Create a pod serving request for a VOD stream. - request = [[IMAPodVODStreamRequest alloc] initWithNetworkCode:kNetworkCode + // VOD request. Replace the network code with your value. + request = [[IMAPodVODStreamRequest alloc] initWithNetworkCode:@kNetworkCode adDisplayContainer:adDisplayContainer videoDisplay:self.videoDisplay pictureInPictureProxy:nil @@ -123,43 +123,41 @@ - (void)requestStream { } [self.adsLoader requestStreamWithRequest:request]; } +// [END make_stream_request] -#pragma mark AdsLoader Delegates - +// [START ads_loader_delegates] - (void)adsLoader:(IMAAdsLoader *)loader adsLoadedWithData:(IMAAdsLoadedData *)adsLoadedData { - // Initialize and listen to stream manager's events. + NSLog(@"Stream created with: %@.", adsLoadedData.streamManager.streamId); self.streamManager = adsLoadedData.streamManager; - // The stream manager must be initialized before playback for adsRenderingSettings to be - // respected. - [self.streamManager initializeWithAdsRenderingSettings:nil]; self.streamManager.delegate = self; - // Build the Pod serving Stream URL and load into AVPlayer - NSString *streamId = adsLoadedData.streamManager.streamId; - NSString *urlString = gCustomVTPParser(streamId); + // Build the Pod serving Stream URL. + NSString *streamID = adsLoadedData.streamManager.streamId; + // Your custom VTP handler takes the stream ID and returns the stream manifest URL. + NSString *urlString = gCustomVTPHandler(streamID); NSURL *streamUrl = [NSURL URLWithString:urlString]; - if (kRequestType == liveStream) { + if (kStreamType == StreamTypeLive) { + // Load live streams directly into the AVPlayer. [self.videoDisplay loadStream:streamUrl withSubtitles:@[]]; [self.videoDisplay play]; } else { + // Load VOD streams using the `loadThirdPartyStream` method in IMA SDK's stream manager. + // The stream manager loads the stream, requests metadata, and starts playback. [self.streamManager loadThirdPartyStream:streamUrl streamSubtitles:@[]]; - // There is no need to trigger playback here. - // streamManager.loadThirdPartyStream will load the stream, request metadata, and play } - NSLog(@"Stream created with: %@.", self.streamManager.streamId); } - (void)adsLoader:(IMAAdsLoader *)loader failedWithErrorData:(IMAAdLoadingErrorData *)adErrorData { - // Something went wrong loading ads. Log the error and play the content. + // Log the error and play the content. NSLog(@"AdsLoader error, code:%ld, message: %@", adErrorData.adError.code, adErrorData.adError.message); - [self.contentPlayer play]; + [self.videoPlayer play]; } +// [END ads_loader_delegates] -#pragma mark StreamManager Delegates - +// [START stream_manager_delegates] - (void)streamManager:(IMAStreamManager *)streamManager didReceiveAdEvent:(IMAAdEvent *)event { - NSLog(@"StreamManager event (%@).", event.typeString); + NSLog(@"Ad event (%@).", event.typeString); switch (event.type) { case kIMAAdEvent_STARTED: { // Log extended data. @@ -199,7 +197,8 @@ - (void)streamManager:(IMAStreamManager *)streamManager didReceiveAdEvent:(IMAAd - (void)streamManager:(IMAStreamManager *)streamManager didReceiveAdError:(IMAAdError *)error { NSLog(@"StreamManager error with type: %ld\ncode: %ld\nmessage: %@", error.type, error.code, error.message); - [self.contentPlayer play]; + [self.videoPlayer play]; } +// [END stream_manager_delegates] @end diff --git a/Swift/BasicExample/app/ViewController.swift b/Swift/BasicExample/app/ViewController.swift index d9cc623..e7bfa03 100644 --- a/Swift/BasicExample/app/ViewController.swift +++ b/Swift/BasicExample/app/ViewController.swift @@ -12,82 +12,93 @@ // permissions and limitations under the License. import AVFoundation +// [START import_ima_sdk] import GoogleInteractiveMediaAds +// [START_EXCLUDE] import UIKit +// [END_EXCLUDE] class ViewController: UIViewController, IMAAdsLoaderDelegate, IMAStreamManagerDelegate { - enum StreamType { case liveStream, vodStream } - // Stream request type. Either `StreamType.liveStream` or `StreamType.vodStream`. - static let requestType = StreamType.liveStream - // Live stream asset keys. + // [START_EXCLUDE] + enum StreamType { case live, vod } + + /// Specifies the ad pod stream type; either `StreamType.live` or `StreamType.vod`. + /// + /// Change to `StreamType.vod` to make a VOD request. + static let requestType = StreamType.live + /// Live stream asset key. static let assetKey = "c-rArva4ShKVIAkNfy6HUQ" - // VOD content source and video ID. + /// VOD content source ID. static let contentSourceID = "2548831" + /// VOD video ID. static let videoID = "tears-of-steel" - // Backup content URL - static let backupStreamURLString = """ - http://googleimadev-vh.akamaihd.net/i/big_buck_bunny/\ - bbb-,480p,720p,1080p,.mov.csmil/master.m3u8 - """ + /// The backup stream is only played when an error is detected during the stream creation. + static let backupStreamURLString = + "http://devimages.apple.com/iphone/samples/bipbop/bipbopall.m3u8" + // [END_EXCLUDE] + + /// The entry point for the IMA DAI SDK to make DAI stream requests. private var adsLoader: IMAAdsLoader? - private var videoDisplay: IMAAVPlayerVideoDisplay! + /// The container where the SDK renders each ad's user interface elements and companion slots. private var adDisplayContainer: IMAAdDisplayContainer? + /// The reference of your video player for the IMA DAI SDK to monitor playback and handle timed + /// metadata. + private var imaVideoDisplay: IMAAVPlayerVideoDisplay! + /// References the stream manager from the IMA DAI SDK after successful stream loading. private var streamManager: IMAStreamManager? - private var contentPlayhead: IMAAVPlayerContentPlayhead? - private var playerViewController: AVPlayerViewController! - private var userSeekTime = 0.0 - private var adBreakActive = false - private var contentPlayer: AVPlayer? + // [START_EXCLUDE] + /// Play button. @IBOutlet private weak var playButton: UIButton! + @IBOutlet private weak var videoView: UIView! + /// Video player to play the DAI stream for both content and ads. + private var videoPlayer: AVPlayer? + // [END_EXCLUDE] override func viewDidLoad() { super.viewDidLoad() + // [START_EXCLUDE] playButton.layer.zPosition = CGFloat(MAXFLOAT) - setupAdsLoader() - setUpPlayer() - } - - @IBAction func onPlayButtonTouch(_ sender: Any) { - requestStream() - playButton.isHidden = true - } - - // MARK: Content Player Setup - - func setUpPlayer() { // Load AVPlayer with path to our content. - contentPlayer = AVPlayer() + let contentURL = URL(string: ViewController.backupStreamURLString)! + videoPlayer = AVPlayer(url: contentURL) // Create a player layer for the player. - let playerLayer = AVPlayerLayer(player: contentPlayer) + let playerLayer = AVPlayerLayer(player: videoPlayer) // Size, position, and display the AVPlayer. playerLayer.frame = videoView.layer.bounds videoView.layer.addSublayer(playerLayer) - } - - // MARK: SDK Setup + // [END_EXCLUDE] - func setupAdsLoader() { adsLoader = IMAAdsLoader(settings: nil) adsLoader?.delegate = self - } - func requestStream() { - // Create an ad display container for ad rendering. + // Create an ad display container for rendering each ad's user interface elements and companion + // slots. adDisplayContainer = IMAAdDisplayContainer( adContainer: videoView, viewController: self, companionSlots: nil) + // Create an IMAAVPlayerVideoDisplay to give the SDK access to your video player. - let imaVideoDisplay = IMAAVPlayerVideoDisplay(avPlayer: contentPlayer!) + imaVideoDisplay = IMAAVPlayerVideoDisplay(avPlayer: videoPlayer) + } + // [END import_ima_sdk] + + // [START make_stream_request] + @IBAction func onPlayButtonTouch(_ sender: Any) { + requestStream() + playButton.isHidden = true + } + + func requestStream() { // Create a stream request. Use one of "Livestream request" or "VOD request". - if ViewController.requestType == StreamType.liveStream { + if ViewController.requestType == StreamType.live { // Livestream request. let request = IMALiveStreamRequest( assetKey: ViewController.assetKey, @@ -106,15 +117,12 @@ class ViewController: UIViewController, IMAAdsLoaderDelegate, IMAStreamManagerDe adsLoader?.requestStream(with: request) } } - - func startMediaSession() { - try? AVAudioSession.sharedInstance().setActive(true, options: []) - try? AVAudioSession.sharedInstance().setCategory(.playback) - } + // [END make_stream_request] // MARK: - IMAAdsLoaderDelegate - + // [START ads_loader_delegates] func adsLoader(_ loader: IMAAdsLoader, adsLoadedWith adsLoadedData: IMAAdsLoadedData) { + print("Stream created with: \(String(describing: adsLoadedData.streamManager!.streamID))") streamManager = adsLoadedData.streamManager! streamManager!.delegate = self streamManager!.initialize(with: nil) @@ -123,14 +131,14 @@ class ViewController: UIViewController, IMAAdsLoaderDelegate, IMAStreamManagerDe func adsLoader(_ loader: IMAAdsLoader, failedWith adErrorData: IMAAdLoadingErrorData) { print("Error loading ads: \(String(describing: adErrorData.adError.message))") let streamURL = URL(string: ViewController.backupStreamURLString) - videoDisplay.loadStream(streamURL!, withSubtitles: []) - videoDisplay.play() - playerViewController.player?.play() + videoPlayer.play() } + // [END ads_loader_delegates] // MARK: - IMAStreamManagerDelegate + // [START stream_manager_delegates] func streamManager(_ streamManager: IMAStreamManager, didReceive event: IMAAdEvent) { - print("StreamManager event \(event.typeString).") + print("Ad event \(event.typeString).") switch event.type { case IMAAdEventType.STREAM_STARTED: self.startMediaSession() @@ -155,16 +163,16 @@ class ViewController: UIViewController, IMAAdsLoaderDelegate, IMAStreamManagerDe } break case IMAAdEventType.AD_BREAK_STARTED: - // Trigger an update to send focus to the ad display container. - adBreakActive = true + print("Ad break started.") break case IMAAdEventType.AD_BREAK_ENDED: - // Trigger an update to send focus to the content player. - adBreakActive = false + print("Ad break ended.") + break + case IMAAdEventType.AD_PERIOD_STARTED: + print("Ad period started.") break - case IMAAdEventType.ICON_FALLBACK_IMAGE_CLOSED: - // Resume playback after the user has closed the dialog. - self.videoDisplay.play() + case IMAAdEventType.AD_PERIOD_ENDED: + print("Ad period ended.") break default: break @@ -172,18 +180,9 @@ class ViewController: UIViewController, IMAAdsLoaderDelegate, IMAStreamManagerDe } func streamManager(_ streamManager: IMAStreamManager, didReceive error: IMAAdError) { - print("StreamManager error: \(error.message ?? "Unknown Error")") - } - - // MARK: - AVPlayerViewControllerDelegate - func playerViewController( - _ playerViewController: AVPlayerViewController, - timeToSeekAfterUserNavigatedFrom oldTime: CMTime, - to targetTime: CMTime - ) -> CMTime { - if adBreakActive { - return oldTime - } - return targetTime + print("StreamManager error with type: \(error.type ?? "Unknown Error")") + print("code: \(error.code ?? "Unknown Error")") + print("message: \(error.message ?? "Unknown Error")") } + // [END stream_manager_delegates] } diff --git a/Swift/PodServingExample/app/ViewController.swift b/Swift/PodServingExample/app/ViewController.swift index 2af4df2..2dc17d9 100644 --- a/Swift/PodServingExample/app/ViewController.swift +++ b/Swift/PodServingExample/app/ViewController.swift @@ -12,144 +12,160 @@ // permissions and limitations under the License. import AVFoundation +// [START import_ima_sdk] import GoogleInteractiveMediaAds +// [START_EXCLUDE] import UIKit +// [END_EXCLUDE] -// The main view controller for the sample app. class ViewController: UIViewController, IMAAdsLoaderDelegate, IMAStreamManagerDelegate { - enum StreamType { case liveStream, vodStream } - /// Specifies the ad pod stream type; either `StreamType.liveStream` or `StreamType.vodStream`. - static let requestType = StreamType.liveStream + // [START_EXCLUDE] + enum StreamType { case live, vod } + + /// Specifies the ad pod stream type; either `StreamType.live` or `StreamType.vod`. + /// + /// Change to `StreamType.vod` to make a VOD request. + static let requestType = StreamType.live /// Google Ad Manager network code. - static let networkCode = "" + static let networkCode = "YOUR_NETWORK_CODE" /// Livestream custom asset key. - static let customAssetKey = "" + static let customAssetKey = "YOUR_CUSTOM_ASSET_KEY" + // [START custom_vtp_handler] + /// Custom VTP Handler. + /// /// Returns the stream manifest URL from the video technical partner or manifest manipulator. static let customVTPParser = { (streamID: String) -> (String) in // Insert synchronous code here to retrieve a stream manifest URL from your video tech partner // or manifest manipulation server. - let manifestURL = "" - return manifestURL + // This example uses a hardcoded URL template, containing a placeholder for the stream + // ID and replaces the placeholder with the stream ID. + let manifestURL = "YOUR_MANIFEST_URL_TEMPLATE" + return manifestURL.replacingOccurrences(of: "[[STREAMID]]", with: streamID) } + // [END custom_vtp_handler] - static let backupStreamURLString = "" + /// The backup stream is only played when an error is detected during the stream creation. + static let backupStreamURLString = + "http://devimages.apple.com/iphone/samples/bipbop/bipbopall.m3u8" + // [END_EXCLUDE] + /// The entry point for the IMA DAI SDK to make DAI stream requests. private var adsLoader: IMAAdsLoader? - private var videoDisplay: IMAAVPlayerVideoDisplay! + /// The container where the SDK renders each ad's user interface elements and companion slots. private var adDisplayContainer: IMAAdDisplayContainer? + /// The reference of your video player for the IMA DAI SDK to monitor playback and handle timed + /// metadata. + private var imaVideoDisplay: IMAAVPlayerVideoDisplay! + /// References the stream manager from the IMA DAI SDK after successful stream loading. private var streamManager: IMAStreamManager? - private var contentPlayhead: IMAAVPlayerContentPlayhead? - private var playerViewController: AVPlayerViewController! - private var userSeekTime = 0.0 - private var adBreakActive = false - private var contentPlayer: AVPlayer? + // [START_EXCLUDE] + /// Play button. @IBOutlet private weak var playButton: UIButton! + @IBOutlet private weak var videoView: UIView! + /// Video player to play the DAI stream for both content and ads. + private var videoPlayer: AVPlayer? + // [END_EXCLUDE] override func viewDidLoad() { super.viewDidLoad() + // [START_EXCLUDE] playButton.layer.zPosition = CGFloat(MAXFLOAT) - setupAdsLoader() - setUpPlayer() - } - - @IBAction func onPlayButtonTouch(_ sender: Any) { - requestStream() - playButton.isHidden = true - } - - // MARK: Content Player Setup - - func setUpPlayer() { // Load AVPlayer with path to our content. - contentPlayer = AVPlayer() + let contentURL = URL(string: ViewController.backupStreamURLString)! + videoPlayer = AVPlayer(url: contentURL) // Create a player layer for the player. - let playerLayer = AVPlayerLayer(player: contentPlayer) + let playerLayer = AVPlayerLayer(player: videoPlayer) // Size, position, and display the AVPlayer. playerLayer.frame = videoView.layer.bounds videoView.layer.addSublayer(playerLayer) - } - - // MARK: SDK Setup + // [END_EXCLUDE] - func setupAdsLoader() { adsLoader = IMAAdsLoader(settings: nil) adsLoader?.delegate = self - } - func requestStream() { - // Create an ad display container for ad rendering. + // Create an ad display container for rendering each ad's user interface elements and companion + // slots. adDisplayContainer = IMAAdDisplayContainer( adContainer: videoView, viewController: self, companionSlots: nil) + // Create an IMAAVPlayerVideoDisplay to give the SDK access to your video player. - self.videoDisplay = IMAAVPlayerVideoDisplay(avPlayer: contentPlayer!) - let streamRequest: IMAStreamRequest - if ViewController.requestType == StreamType.liveStream { - // Create a pod serving live stream request. - streamRequest = IMAPodStreamRequest( + imaVideoDisplay = IMAAVPlayerVideoDisplay(avPlayer: videoPlayer) + } + // [END import_ima_sdk] + + // [START make_stream_request] + @IBAction func onPlayButtonTouch(_ sender: Any) { + requestStream() + playButton.isHidden = true + } + + func requestStream() { + // Create a stream request. Use one of "Livestream request" or "VOD request". + if ViewController.requestType == StreamType.live { + // Livestream request. + let request = IMAPodStreamRequest( networkCode: ViewController.networkCode, customAssetKey: ViewController.customAssetKey, adDisplayContainer: adDisplayContainer!, videoDisplay: self.videoDisplay, pictureInPictureProxy: nil, userContext: nil) + adsLoader?.requestStream(with: request) } else { - // Create a pod serving VOD stream request. - streamRequest = IMAPodVODStreamRequest( + // VOD stream request. + let request = IMAPodVODStreamRequest( networkCode: ViewController.networkCode, adDisplayContainer: adDisplayContainer!, videoDisplay: self.videoDisplay, pictureInPictureProxy: nil, userContext: nil) + adsLoader?.requestStream(with: request) } - - adsLoader?.requestStream(with: streamRequest) - } - - func startMediaSession() { - try? AVAudioSession.sharedInstance().setActive(true, options: []) - try? AVAudioSession.sharedInstance().setCategory(.playback) } + // [END make_stream_request] // MARK: - IMAAdsLoaderDelegate - + // [START ads_loader_delegates] func adsLoader(_ loader: IMAAdsLoader, adsLoadedWith adsLoadedData: IMAAdsLoadedData) { - self.streamManager = adsLoadedData.streamManager! - self.streamManager?.delegate = self - // The stream manager must be initialized before playback for adsRenderingSettings to be - // respected. - self.streamManager?.initialize(with: nil) - let streamID = self.streamManager?.streamId + print("Stream created with: \(String(describing: adsLoadedData.streamManager!.streamID))") + streamManager = adsLoadedData.streamManager! + streamManager!.delegate = self + + // Build the Pod serving Stream URL. + let streamID = streamManager!.streamId + // Your custom VTP handler takes the stream ID and returns the stream manifest URL. let urlString = ViewController.customVTPParser(streamID!) let streamUrl = URL(string: urlString) - if ViewController.requestType == StreamType.liveStream { - self.videoDisplay.loadStream(streamUrl!, withSubtitles: []) - self.videoDisplay.play() + if ViewController.requestType == StreamType.live { + // Live streams can be loaded directly into the AVPlayer. + imaVideoDisplay.loadStream(streamUrl!, withSubtitles: []) + imaVideoDisplay.play() } else { - self.streamManager?.loadThirdPartyStream(streamUrl!, streamSubtitles: []) - // Skip calling self.videoDisplay.play() because the streamManager.loadThirdPartyStream() - // function will play the stream as soon as loading is completed. + // VOD streams are loaded via the IMA SDK's stream manager. + // The stream manager loads the stream, requests metadata, and starts playback. + streamManager!.loadThirdPartyStream(streamUrl!, streamSubtitles: []) } } func adsLoader(_ loader: IMAAdsLoader, failedWith adErrorData: IMAAdLoadingErrorData) { print("Error loading ads: \(String(describing: adErrorData.adError.message))") let streamURL = URL(string: ViewController.backupStreamURLString) - videoDisplay.loadStream(streamURL!, withSubtitles: []) - videoDisplay.play() - playerViewController.player?.play() + videoPlayer.play() } + // [END ads_loader_delegates] // MARK: - IMAStreamManagerDelegate + // [START stream_manager_delegates] func streamManager(_ streamManager: IMAStreamManager, didReceive event: IMAAdEvent) { - print("StreamManager event \(event.typeString).") + print("Ad event \(event.typeString).") switch event.type { case IMAAdEventType.STREAM_STARTED: self.startMediaSession() @@ -174,16 +190,16 @@ class ViewController: UIViewController, IMAAdsLoaderDelegate, IMAStreamManagerDe } break case IMAAdEventType.AD_BREAK_STARTED: - // Trigger an update to send focus to the ad display container. - adBreakActive = true + print("Ad break started.") break case IMAAdEventType.AD_BREAK_ENDED: - // Trigger an update to send focus to the content player. - adBreakActive = false + print("Ad break ended.") break - case IMAAdEventType.ICON_FALLBACK_IMAGE_CLOSED: - // Resume playback after the user has closed the dialog. - self.videoDisplay.play() + case IMAAdEventType.AD_PERIOD_STARTED: + print("Ad period started.") + break + case IMAAdEventType.AD_PERIOD_ENDED: + print("Ad period ended.") break default: break @@ -191,18 +207,9 @@ class ViewController: UIViewController, IMAAdsLoaderDelegate, IMAStreamManagerDe } func streamManager(_ streamManager: IMAStreamManager, didReceive error: IMAAdError) { - print("StreamManager error: \(error.message ?? "Unknown Error")") - } - - // MARK: - AVPlayerViewControllerDelegate - func playerViewController( - _ playerViewController: AVPlayerViewController, - timeToSeekAfterUserNavigatedFrom oldTime: CMTime, - to targetTime: CMTime - ) -> CMTime { - if adBreakActive { - return oldTime - } - return targetTime + print("StreamManager error with type: \(error.type ?? "Unknown Error")") + print("code: \(error.code ?? "Unknown Error")") + print("message: \(error.message ?? "Unknown Error")") } + // [END stream_manager_delegates] } diff --git a/Swift/SampleVideoPlayer/SampleVideoPlayer.xcodeproj/project.pbxproj b/Swift/SampleVideoPlayer/SampleVideoPlayer.xcodeproj/project.pbxproj new file mode 100644 index 0000000..a8a7855 --- /dev/null +++ b/Swift/SampleVideoPlayer/SampleVideoPlayer.xcodeproj/project.pbxproj @@ -0,0 +1,368 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 56; + objects = { + +/* Begin PBXBuildFile section */ + D20D1DC82C1652260021D157 /* iPhone.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = D20D1DC62C1652260021D157 /* iPhone.storyboard */; }; + D20D1DC92C1652260021D157 /* iPad.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = D20D1DC72C1652260021D157 /* iPad.storyboard */; }; + D21627942C165053004B08EF /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = D21627932C165053004B08EF /* AppDelegate.swift */; }; + D21627982C165053004B08EF /* ViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = D21627972C165053004B08EF /* ViewController.swift */; }; + D21627A02C165055004B08EF /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = D216279F2C165055004B08EF /* Assets.xcassets */; }; +/* End PBXBuildFile section */ + +/* Begin PBXFileReference section */ + D20D1DC62C1652260021D157 /* iPhone.storyboard */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.storyboard; path = iPhone.storyboard; sourceTree = ""; }; + D20D1DC72C1652260021D157 /* iPad.storyboard */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.storyboard; path = iPad.storyboard; sourceTree = ""; }; + D21627902C165053004B08EF /* SampleVideoPlayer.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = SampleVideoPlayer.app; sourceTree = BUILT_PRODUCTS_DIR; }; + D21627932C165053004B08EF /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; + D21627972C165053004B08EF /* ViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ViewController.swift; sourceTree = ""; }; + D216279F2C165055004B08EF /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; + D21627A42C165055004B08EF /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + D216278D2C165053004B08EF /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + C3F09BE363D05255D29BD1ED /* Pods */ = { + isa = PBXGroup; + children = ( + ); + path = Pods; + sourceTree = ""; + }; + D21627872C165053004B08EF = { + isa = PBXGroup; + children = ( + D21627922C165053004B08EF /* SampleVideoPlayer */, + D21627912C165053004B08EF /* Products */, + C3F09BE363D05255D29BD1ED /* Pods */, + ); + sourceTree = ""; + }; + D21627912C165053004B08EF /* Products */ = { + isa = PBXGroup; + children = ( + D21627902C165053004B08EF /* SampleVideoPlayer.app */, + ); + name = Products; + sourceTree = ""; + }; + D21627922C165053004B08EF /* SampleVideoPlayer */ = { + isa = PBXGroup; + children = ( + D21627932C165053004B08EF /* AppDelegate.swift */, + D21627972C165053004B08EF /* ViewController.swift */, + D216279F2C165055004B08EF /* Assets.xcassets */, + D20D1DC72C1652260021D157 /* iPad.storyboard */, + D20D1DC62C1652260021D157 /* iPhone.storyboard */, + D21627A42C165055004B08EF /* Info.plist */, + ); + name = SampleVideoPlayer; + path = app; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + D216278F2C165053004B08EF /* SampleVideoPlayer */ = { + isa = PBXNativeTarget; + buildConfigurationList = D21627A72C165055004B08EF /* Build configuration list for PBXNativeTarget "SampleVideoPlayer" */; + buildPhases = ( + D216278C2C165053004B08EF /* Sources */, + D216278D2C165053004B08EF /* Frameworks */, + D216278E2C165053004B08EF /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = SampleVideoPlayer; + productName = SampleVideoPlayer; + productReference = D21627902C165053004B08EF /* SampleVideoPlayer.app */; + productType = "com.apple.product-type.application"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + D21627882C165053004B08EF /* Project object */ = { + isa = PBXProject; + attributes = { + BuildIndependentTargetsInParallel = 1; + LastSwiftUpdateCheck = 1530; + LastUpgradeCheck = 1530; + TargetAttributes = { + D216278F2C165053004B08EF = { + CreatedOnToolsVersion = 15.3; + }; + }; + }; + buildConfigurationList = D216278B2C165053004B08EF /* Build configuration list for PBXProject "SampleVideoPlayer" */; + compatibilityVersion = "Xcode 14.0"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = D21627872C165053004B08EF; + productRefGroup = D21627912C165053004B08EF /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + D216278F2C165053004B08EF /* SampleVideoPlayer */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + D216278E2C165053004B08EF /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + D21627A02C165055004B08EF /* Assets.xcassets in Resources */, + D20D1DC92C1652260021D157 /* iPad.storyboard in Resources */, + D20D1DC82C1652260021D157 /* iPhone.storyboard in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + D216278C2C165053004B08EF /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + D21627982C165053004B08EF /* ViewController.swift in Sources */, + D21627942C165053004B08EF /* AppDelegate.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin XCBuildConfiguration section */ + D21627A52C165055004B08EF /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++20"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu17; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 17.4; + LOCALIZATION_PREFERS_STRING_CATALOGS = YES; + MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; + MTL_FAST_MATH = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = iphoneos; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "DEBUG $(inherited)"; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + }; + name = Debug; + }; + D21627A62C165055004B08EF /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++20"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu17; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 17.4; + LOCALIZATION_PREFERS_STRING_CATALOGS = YES; + MTL_ENABLE_DEBUG_INFO = NO; + MTL_FAST_MATH = YES; + SDKROOT = iphoneos; + SWIFT_COMPILATION_MODE = wholemodule; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; + D21627A82C165055004B08EF /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + DEVELOPMENT_TEAM = Z95L3YYF93; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GENERATE_INFOPLIST_FILE = YES; + INFOPLIST_FILE = app/Info.plist; + INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents = YES; + INFOPLIST_KEY_UILaunchStoryboardName = iPhone.storyboard; + INFOPLIST_KEY_UIMainStoryboardFile = iPhone; + INFOPLIST_KEY_UIRequiredDeviceCapabilities = arm64; + INFOPLIST_KEY_UISupportedInterfaceOrientations = UIInterfaceOrientationPortrait; + INFOPLIST_KEY_UISupportedInterfaceOrientations_iPad = "UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight"; + INFOPLIST_KEY_UISupportedInterfaceOrientations_iPhone = "UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = google.SampleVideoPlayer; + PRODUCT_NAME = "$(TARGET_NAME)"; + SUPPORTED_PLATFORMS = "iphoneos iphonesimulator"; + SUPPORTS_MACCATALYST = NO; + SUPPORTS_MAC_DESIGNED_FOR_IPHONE_IPAD = NO; + SUPPORTS_XR_DESIGNED_FOR_IPHONE_IPAD = NO; + SWIFT_EMIT_LOC_STRINGS = YES; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Debug; + }; + D21627A92C165055004B08EF /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + DEVELOPMENT_TEAM = Z95L3YYF93; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GENERATE_INFOPLIST_FILE = YES; + INFOPLIST_FILE = app/Info.plist; + INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents = YES; + INFOPLIST_KEY_UILaunchStoryboardName = iPhone.storyboard; + INFOPLIST_KEY_UIMainStoryboardFile = iPhone; + INFOPLIST_KEY_UIRequiredDeviceCapabilities = arm64; + INFOPLIST_KEY_UISupportedInterfaceOrientations = UIInterfaceOrientationPortrait; + INFOPLIST_KEY_UISupportedInterfaceOrientations_iPad = "UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight"; + INFOPLIST_KEY_UISupportedInterfaceOrientations_iPhone = "UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = google.SampleVideoPlayer; + PRODUCT_NAME = "$(TARGET_NAME)"; + SUPPORTED_PLATFORMS = "iphoneos iphonesimulator"; + SUPPORTS_MACCATALYST = NO; + SUPPORTS_MAC_DESIGNED_FOR_IPHONE_IPAD = NO; + SUPPORTS_XR_DESIGNED_FOR_IPHONE_IPAD = NO; + SWIFT_EMIT_LOC_STRINGS = YES; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + D216278B2C165053004B08EF /* Build configuration list for PBXProject "SampleVideoPlayer" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + D21627A52C165055004B08EF /* Debug */, + D21627A62C165055004B08EF /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + D21627A72C165055004B08EF /* Build configuration list for PBXNativeTarget "SampleVideoPlayer" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + D21627A82C165055004B08EF /* Debug */, + D21627A92C165055004B08EF /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = D21627882C165053004B08EF /* Project object */; +} diff --git a/Swift/SampleVideoPlayer/SampleVideoPlayer.xcodeproj/xcshareddata/xcschemes/SampleVideoPlayer.xcscheme b/Swift/SampleVideoPlayer/SampleVideoPlayer.xcodeproj/xcshareddata/xcschemes/SampleVideoPlayer.xcscheme new file mode 100644 index 0000000..17455cd --- /dev/null +++ b/Swift/SampleVideoPlayer/SampleVideoPlayer.xcodeproj/xcshareddata/xcschemes/SampleVideoPlayer.xcscheme @@ -0,0 +1,85 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Swift/SampleVideoPlayer/app/AppDelegate.swift b/Swift/SampleVideoPlayer/app/AppDelegate.swift new file mode 100644 index 0000000..126585f --- /dev/null +++ b/Swift/SampleVideoPlayer/app/AppDelegate.swift @@ -0,0 +1,29 @@ +// Copyright 2024 Google LLC. All rights reserved. +// +// +// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this +// file except in compliance with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software distributed under +// the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF +// ANY KIND, either express or implied. See the License for the specific language governing +// permissions and limitations under the License. + +import CoreData +import UIKit + +@main class AppDelegate: UIResponder, UIApplicationDelegate { + + var window: UIWindow? + + func application( + _ application: UIApplication, + didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? + ) -> Bool { + // Override point for customization after application launch. + return true + } + +} diff --git a/Swift/SampleVideoPlayer/app/Assets.xcassets/AccentColor.colorset/Contents.json b/Swift/SampleVideoPlayer/app/Assets.xcassets/AccentColor.colorset/Contents.json new file mode 100644 index 0000000..eb87897 --- /dev/null +++ b/Swift/SampleVideoPlayer/app/Assets.xcassets/AccentColor.colorset/Contents.json @@ -0,0 +1,11 @@ +{ + "colors" : [ + { + "idiom" : "universal" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/Swift/SampleVideoPlayer/app/Assets.xcassets/AppIcon.appiconset/Contents.json b/Swift/SampleVideoPlayer/app/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 0000000..13613e3 --- /dev/null +++ b/Swift/SampleVideoPlayer/app/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,13 @@ +{ + "images" : [ + { + "idiom" : "universal", + "platform" : "ios", + "size" : "1024x1024" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/Swift/SampleVideoPlayer/app/Assets.xcassets/Contents.json b/Swift/SampleVideoPlayer/app/Assets.xcassets/Contents.json new file mode 100644 index 0000000..73c0059 --- /dev/null +++ b/Swift/SampleVideoPlayer/app/Assets.xcassets/Contents.json @@ -0,0 +1,6 @@ +{ + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/Swift/SampleVideoPlayer/app/Info.plist b/Swift/SampleVideoPlayer/app/Info.plist new file mode 100644 index 0000000..5ff527f --- /dev/null +++ b/Swift/SampleVideoPlayer/app/Info.plist @@ -0,0 +1,15 @@ + + + + + NSAppTransportSecurity + + NSAllowsArbitraryLoads + + + UIMainStoryboardFile~ipad + iPad + UIMainStoryboardFile~iphone + iPhone + + diff --git a/Swift/SampleVideoPlayer/app/ViewController.swift b/Swift/SampleVideoPlayer/app/ViewController.swift new file mode 100644 index 0000000..fd68143 --- /dev/null +++ b/Swift/SampleVideoPlayer/app/ViewController.swift @@ -0,0 +1,51 @@ +// Copyright 2024 Google LLC. All rights reserved. +// +// +// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this +// file except in compliance with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software distributed under +// the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF +// ANY KIND, either express or implied. See the License for the specific language governing +// permissions and limitations under the License. + +import AVFoundation +import UIKit + +class ViewController: UIViewController { + + /// Content URL. + static let backupStreamURLString = + "http://devimages.apple.com/iphone/samples/bipbop/bipbopall.m3u8" + + /// Play button. + @IBOutlet private weak var playButton: UIButton! + + @IBOutlet private weak var videoView: UIView! + /// Video player. + private var videoPlayer: AVPlayer? + + override func viewDidLoad() { + super.viewDidLoad() + + playButton.layer.zPosition = CGFloat(MAXFLOAT) + + // Load AVPlayer with path to our content. + let contentURL = URL(string: ViewController.backupStreamURLString)! + videoPlayer = AVPlayer(url: contentURL) + + // Create a player layer for the player. + let playerLayer = AVPlayerLayer(player: videoPlayer) + + // Size, position, and display the AVPlayer. + playerLayer.frame = videoView.layer.bounds + videoView.layer.addSublayer(playerLayer) + } + + @IBAction func onPlayButtonTouch(_ sender: Any) { + videoPlayer.play() + playButton.isHidden = true + } +} diff --git a/Swift/SampleVideoPlayer/app/iPad.storyboard b/Swift/SampleVideoPlayer/app/iPad.storyboard new file mode 100644 index 0000000..54010e0 --- /dev/null +++ b/Swift/SampleVideoPlayer/app/iPad.storyboard @@ -0,0 +1,59 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Swift/SampleVideoPlayer/app/iPhone.storyboard b/Swift/SampleVideoPlayer/app/iPhone.storyboard new file mode 100644 index 0000000..b74d458 --- /dev/null +++ b/Swift/SampleVideoPlayer/app/iPhone.storyboard @@ -0,0 +1,59 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +