YouTube 도우미 라이브러리를 사용하여 iOS 애플리케이션에 YouTube 동영상 삽입
컬렉션을 사용해 정리하기
내 환경설정을 기준으로 콘텐츠를 저장하고 분류하세요.
youtube-ios-player-helper
는 iOS 애플리케이션에 YouTube iframe 플레이어를 삽입하는 데 도움이 되는 오픈소스 라이브러리입니다. 라이브러리는 WebView
및 애플리케이션의 Objective-C 코드와 YouTube 플레이어의 자바스크립트 코드 간의 브리지를 만들어 iOS 애플리케이션이 YouTube 플레이어를 제어할 수 있도록 합니다. 이 도움말에서는 iOS 애플리케이션에서 라이브러리를 설치하고 사용하기 위한 단계를 설명합니다.
설치
이 도움말에서는 개발자가 최신 버전의 iOS를 타겟팅하는 새로운 단일 뷰 애플리케이션 iOS 프로젝트를 만들고 프로젝트를 만들 때 다음 파일을 추가한다고 가정합니다.
Main.storyboard
ViewController.h
ViewController.m
CocoaPods를 통하거나 프로젝트의 GitHub 페이지에서 라이브러리 및 소스 파일을 복사하여 라이브러리를 설치할 수 있습니다.
- 라이브러리는 CocoaPods를 통해 설치할 수 있습니다. 또는 라이브러리 및 소스 파일을 프로젝트의 GitHub 페이지를 통해 제공하고 기존 프로젝트에 복사할 수 있습니다.
CocoaPods를 통해 라이브러리 설치
프로젝트에서 CocoaPods를 사용하는 경우 아래 파일에 Podfile을 추가하여 라이브러리를 설치하세요.
그 줄에서 x.y.z
를 프로젝트의 GitHub 페이지에서 확인할 최신 포드 버전으로 바꿉니다.
pod "youtube-ios-player-helper", "~> x.y.z"
명령줄 프롬프트에서 pod install
를 입력하여 작업공간을 종속 항목으로 업데이트합니다.
도움말: CocoaPods를 사용할 때 .xcodeproj
파일이 아닌 Xcode에서 .xcworkspace
파일을 열어야 합니다.
자세한 내용은 CocoaPods 가이드를 확인하세요.
수동으로 라이브러리 설치
도우미 라이브러리를 수동으로 설치하려면 GitHub의 다운로드 링크를 통해 소스를 다운로드하거나 저장소를 클론하세요. 코드의 로컬 사본이 있으면 다음 단계를 따르세요.
Xcode 또는 Finder에서 샘플 프로젝트를 엽니다.
YTPlayerView.h
, YTPlayerView.m
, Assets 폴더를 선택합니다. Xcode에서 작업공간을 열면 포드 -> 개발 포드 -> YouTube-Player-iOS-Helper 및 포드 -> 개발 포드 -> YouTube-Player-iOS-Helper -> 리소스에서 사용할 수 있습니다. Finder에서는 이러한 객체를 Classes 및 Assets 디렉터리에 있는 프로젝트의 루트 디렉터리에서 사용할 수 있습니다.
이 파일과 폴더를 프로젝트로 드래그합니다. 항목을 대상 그룹 폴더에 복사 옵션이 선택되어 있는지 확인합니다. 애셋 폴더를 드래그할 때 추가된 폴더의 폴더 참조 만들기 옵션이 선택되어 있는지 확인하세요.
이제 라이브러리가 설치됩니다.
인터페이스 생성 도구 또는 스토리보드를 통해 YTPlayerView
추가
인터페이스 생성 도구 또는 스토리보드를 통해 YTPlayerView
를 추가하려면 다음 단계를 따르세요.
-
UIView
인스턴스를 뷰로 드래그합니다.
-
Identity Inspector를 선택하고 뷰의 클래스를 YTPlayerView
로 변경합니다.
-
ViewController.h
를 열고 다음 헤더를 추가합니다.
#import “YTPlayerView.h”
다음 속성도 추가합니다.
@property(nonatomic, strong) IBOutlet YTPlayerView *playerView;
-
인터페이스 생성 도구에서 이전 단계에서 정의한 뷰 요소에서 뷰 컨트롤러의 playerView
속성에 대한 연결을 만듭니다.
-
이제 ViewController.m
를 열고 viewDidLoad
메서드 끝에 다음 코드를 추가합니다.
[self.playerView loadWithVideoId:@"M7lc1UVf-VE"];
애플리케이션을 빌드하고 실행합니다. 동영상 썸네일이 로드되면 동영상 썸네일을 탭하여 전체 화면 동영상 플레이어를 실행합니다.
동영상 재생 제어하기
ViewController::loadWithVideoId:
메서드에는 개발자가 추가 플레이어 변수를 뷰에 전달할 수 있는 loadWithVideoId:playerVars:
변형이 있습니다. 이러한 플레이어 변수는 IFrame Player API의 플레이어 매개변수에 해당합니다. playsinline
매개변수를 사용하면 동영상이 전체 화면이 아닌 뷰에서 직접 재생할 수 있습니다. 동영상이 인라인으로 재생될 때 포함된 iOS 애플리케이션이 프로그래매틱 방식으로 재생을 제어할 수 있습니다.
loadWithVideoId:
호출을 다음 코드로 바꿉니다.
NSDictionary *playerVars = @{
@"playsinline" : @1,
};
[self.playerView loadWithVideoId:@"M7lc1UVf-VE" playerVars:playerVars];
스토리보드 또는 인터페이스 빌더를 엽니다. 버튼 두 개를 뷰로 드래그하여 재생 및 중지 라벨을 지정합니다. ViewController.h
를 열고 버튼에 매핑될 다음 메서드를 추가합니다.
- (IBAction)playVideo:(id)sender;
- (IBAction)stopVideo:(id)sender;
이제 ViewController.m
를 열고 다음 두 함수를 정의합니다.
- (IBAction)playVideo:(id)sender {
[self.playerView playVideo];
}
- (IBAction)stopVideo:(id)sender {
[self.playerView stopVideo];
}
대부분의 IFrame Player API 함수에는 Objective-C와 동등한 함수가 있지만 일부 이름 지정은 Objective-C 코딩 가이드라인과 좀 더 일치하도록 약간 다를 수 있습니다. 주목할 만한 예외는 동영상 볼륨을 제어하는 메서드입니다. 이러한 메서드는 휴대전화 하드웨어에 의해 제어되거나 MPVolumeView
과 같이 이러한 목적으로 설계된 기본 제공 UIView
인스턴스로 제어되기 때문입니다.
스토리보드 또는 인터페이스 빌더를 열고 Ctrl 키를 누른 상태에서 재생 버튼과 중지 버튼을 playVideo:
및 stopVideo:
메서드에 연결합니다.
이제 애플리케이션을 빌드하고 실행합니다. 동영상 썸네일이 로드되면 플레이어 컨트롤 외에도 네이티브 컨트롤을 사용하여 동영상을 재생 및 중지할 수 있습니다.
플레이어 콜백 처리
재생 상태 변경 및 재생 오류와 같은 재생 이벤트를 프로그래매틱 방식으로 처리하는 것이 유용할 수 있습니다. JavaScript API에서는 이벤트 리스너를 사용하여 이 작업을 수행합니다.
Objective-C에서는 대리인을 사용하면 됩니다.
다음 코드는 클래스가 대리자 프로토콜을 준수하도록 ViewController.h
에서 인터페이스 선언을 업데이트하는 방법을 보여줍니다. ViewController.h
의 인터페이스 선언을 다음과 같이 변경합니다.
@interface ViewController : UIViewController<YTPlayerViewDelegate>
YTPlayerViewDelegate
는 플레이어에서 재생 이벤트를 처리하기 위한 프로토콜입니다.
일부 이벤트를 처리하도록 ViewController.m
를 업데이트하려면 먼저 ViewController
인스턴스를 YTPlayerView
인스턴스의 대리자로 설정해야 합니다. 이렇게 변경하려면 다음 줄을 ViewController.h
의 viewDidLoad
메서드에 추가합니다.
self.playerView.delegate = self;
이제 ViewController.m
에 다음 메서드를 추가합니다.
- (void)playerView:(YTPlayerView *)playerView didChangeToState:(YTPlayerState)state {
switch (state) {
case kYTPlayerStatePlaying:
NSLog(@"Started playback");
break;
case kYTPlayerStatePaused:
NSLog(@"Paused playback");
break;
default:
break;
}
}
애플리케이션을 빌드하고 실행합니다. 플레이어 상태가 변경될 때 Xcode의 로그 출력을 확인합니다.
동영상이 재생되거나 중지되면 업데이트가 표시됩니다.
라이브러리는 편의성과 가독성을 위해 kYT*
접두사로 시작하는 상수를 제공합니다. 이러한 상수의 전체 목록은 YTPlayerView.m
를 참고하세요.
권장사항 및 제한사항
라이브러리는 WebView
를 만들고 기본 플레이어에 필요한 HTML과 자바스크립트를 렌더링하여 IFrame Player API를 기반으로 합니다. 라이브러리의 목표는 최대한 쉽게 사용할 수 있도록 하고 개발자가 패키지에 자주 쓰는 메서드를 번들로 묶는 것입니다. 유의해야 할 몇 가지 제한사항이 있습니다.
- 라이브러리는 여러
YTPlayerView
인스턴스에서 동시 동영상 재생을 지원하지 않습니다. 애플리케이션에 YTPlayerView
인스턴스가 여러 개 있는 경우 다른 인스턴스에서 재생을 시작하기 전에 기존 인스턴스에서 재생을 일시중지하거나 중지하는 것이 좋습니다. 프로젝트와 함께 제공되는 예시 애플리케이션에서 ViewController는 NSNotificationCenter
를 사용하여 재생이 시작되려고 하는 알림을 전달합니다. 다른 ViewController는 알림을 받으며 YTPlayerView
인스턴스에서 재생을 일시중지합니다.
- 가능하면 기존의
YTPlayerView
인스턴스를 재사용합니다. 뷰에서 동영상을 변경해야 할 때 새 UIView
인스턴스 또는 새 YTPlayerView
인스턴스를 만들거나 loadVideoId:
또는 loadPlaylistId:
을 호출하지 마세요. 대신 WebView
를 새로고침하지 않는 cueVideoById:startSeconds:
함수 계열을 사용하세요. 전체 IFrame 플레이어를 로드할 때 눈에 띄는 지연이 있습니다.
- 비공개 동영상은 재생할 수 없지만 일부 공개 동영상은 재생할 수 있습니다. 이 라이브러리는 기존 iframe 플레이어를 래핑하므로 플레이어의 동작은 모바일 브라우저의 웹페이지에 삽입된 플레이어의 동작과 거의 같아야 합니다.
달리 명시되지 않는 한 이 페이지의 콘텐츠에는 Creative Commons Attribution 4.0 라이선스에 따라 라이선스가 부여되며, 코드 샘플에는 Apache 2.0 라이선스에 따라 라이선스가 부여됩니다. 자세한 내용은 Google Developers 사이트 정책을 참조하세요. 자바는 Oracle 및/또는 Oracle 계열사의 등록 상표입니다.
최종 업데이트: 2023-02-22(UTC)
[[["이해하기 쉬움","easyToUnderstand","thumb-up"],["문제가 해결됨","solvedMyProblem","thumb-up"],["기타","otherUp","thumb-up"]],[["필요한 정보가 없음","missingTheInformationINeed","thumb-down"],["너무 복잡함/단계 수가 너무 많음","tooComplicatedTooManySteps","thumb-down"],["오래됨","outOfDate","thumb-down"],["번역 문제","translationIssue","thumb-down"],["샘플/코드 문제","samplesCodeIssue","thumb-down"],["기타","otherDown","thumb-down"]],["최종 업데이트: 2023-02-22(UTC)"],[[["\u003cp\u003eThis library, \u003ccode\u003eyoutube-ios-player-helper\u003c/code\u003e, facilitates embedding a YouTube iframe player within an iOS application by creating a \u003ccode\u003eWebView\u003c/code\u003e and bridging Objective-C code with the player's JavaScript.\u003c/p\u003e\n"],["\u003cp\u003eInstallation is possible via CocoaPods by adding a specific line to the Podfile, or manually by downloading the source code from the project's GitHub page and dragging specific files into your iOS project.\u003c/p\u003e\n"],["\u003cp\u003eA \u003ccode\u003eYTPlayerView\u003c/code\u003e can be added through Interface Builder or Storyboard by dragging a \u003ccode\u003eUIView\u003c/code\u003e, changing its class to \u003ccode\u003eYTPlayerView\u003c/code\u003e, and connecting it to a \u003ccode\u003eplayerView\u003c/code\u003e property in the \u003ccode\u003eViewController.h\u003c/code\u003e file.\u003c/p\u003e\n"],["\u003cp\u003eThe library allows for controlling video playback, enabling inline play and manipulation using the IFrame Player API through Objective-C equivalent methods.\u003c/p\u003e\n"],["\u003cp\u003eThe library allows the handling of playback events, such as start and stop, through a delegate protocol, \u003ccode\u003eYTPlayerViewDelegate\u003c/code\u003e, where the \u003ccode\u003eViewController\u003c/code\u003e conforms to this protocol to capture those events.\u003c/p\u003e\n"]]],["The `youtube-ios-player-helper` library enables embedding and controlling a YouTube iframe player within an iOS app. Installation is via CocoaPods or manual file copying from GitHub. To use, a `YTPlayerView` is added to the storyboard, connected to a `ViewController`, and initialized with a video ID. Playback is controlled through Objective-C methods (e.g., `playVideo`, `stopVideo`) linked to UI elements. Developers can pass player variables, and the library supports delegate-based event handling for playback states. The library is based on the iFrame Player API and includes a few limitations.\n"],null,["# Embed YouTube Videos in iOS Applications with the YouTube Helper Library\n\nThe `youtube-ios-player-helper` is an open source library that helps you embed a\nYouTube iframe player into an iOS application. The library creates a\n`WebView` and a bridge between your application's Objective-C code and the\nYouTube player's JavaScript code, thereby allowing the iOS application to control the\nYouTube player. This article describes the steps to install the library and get started\nusing it from your iOS application.\n\nInstallation\n------------\n\nThis article assumes you have created a new Single View Application iOS project targeting\nthe latest version of iOS, and that you add the following files when creating the\nproject:\n\n- `Main.storyboard`\n- `ViewController.h`\n- `ViewController.m`\n\nYou can install the library via\n[CocoaPods](https://cocoapods.org/) or by copying the library\nand source files from the\n[project's GitHub page](https://github.com/youtube/youtube-ios-player-helper).\n\n- The library is available to install via CocoaPods. Alternatively, the library and source files are available via the project's GitHub page and can be copied into an existing project.\n\n### Install the library via CocoaPods\n\nIf your project uses CocoaPods, add the line below to your Podfile to install the library.\nIn that line, replace `x.y.z` with the latest pod version, which will be\nidentified on the project's GitHub page. \n\n```text\npod \"youtube-ios-player-helper\", \"~\u003e x.y.z\"\n```\n\nAt the command line prompt, type `pod install` to update your workspace with the\ndependencies.\n\nTip: Remember that when using CocoaPods, you must open the `.xcworkspace` file\nin Xcode, not the `.xcodeproj` file.\n\nCheck out the [CocoaPods\ntutorial](https://guides.cocoapods.org/using/getting-started.html) to learn more.\n\n### Manually install the library\n\nTo install the helper library manually, either download the source via\n[GitHub's download link](https://github.com/youtube/youtube-ios-player-helper) or\nclone the repository. Once you have a local copy of the code, follow these steps:\n\n1. Open the sample project in Xcode or Finder.\n\n2. Select `YTPlayerView.h`, `YTPlayerView.m`, and the\n **Assets** folder. If you open the workspace in Xcode, these are available\n under **Pods -\\\u003e Development Pods -\\\u003e YouTube-Player-iOS-Helper** and\n **Pods -\\\u003e Development Pods -\\\u003e YouTube-Player-iOS-Helper -\\\u003e Resources** . In the Finder,\n these are available in the project's root directory in the **Classes** and\n **Assets** directories.\n\n3. Drag these files and folders into your project. Make sure the **Copy items into\n destination group's folder** option is checked. When dragging the Assets folder, make\n sure that the **Create Folder References for any added folders** option is\n checked.\n\nThe library should now be installed.\n\nAdd a `YTPlayerView` via Interface Builder or the Storyboard\n------------------------------------------------------------\n\nTo add a `YTPlayerView` via Interface Builder or the Storyboard:\n\n1. Drag a `UIView` instance onto your View.\n\n2. Select the Identity Inspector and change the class of the view to\n `YTPlayerView`.\n\n3. Open `ViewController.h` and add the following header:\n\n ```objective-c\n #import \"YTPlayerView.h\"\n ```\n\n Also add the following property: \n\n ```objective-c\n @property(nonatomic, strong) IBOutlet YTPlayerView *playerView;\n ```\n4. In Interface Builder, create a connection from the View element that you defined in the\n previous step to your View Controller's `playerView` property.\n\n5. Now open `ViewController.m` and add the following code to the end of your\n `viewDidLoad` method:\n\n ```objective-c\n [self.playerView loadWithVideoId:@\"M7lc1UVf-VE\"];\n ```\n\nBuild and run your application. When the video thumbnail loads, tap the video thumbnail to\nlaunch the fullscreen video player.\n\nControl video playback\n----------------------\n\nThe `ViewController::loadWithVideoId:` method has a variant,\n`loadWithVideoId:playerVars:`, that allows developers to pass additional player\nvariables to the view. These player variables correspond to the\n[player parameters in the\nIFrame Player API](https://developers.google.com/youtube/player_parameters). The `playsinline` parameter enables the video to play\ndirectly in the view rather than playing fullscreen. When a video is playing inline, the\ncontaining iOS application can programmatically control playback.\n\nReplace the `loadWithVideoId:` call with this code: \n\n```objective-c\nNSDictionary *playerVars = @{\n @\"playsinline\" : @1,\n};\n[self.playerView loadWithVideoId:@\"M7lc1UVf-VE\" playerVars:playerVars];\n```\n\nOpen up the storyboard or Interface Builder. Drag two buttons onto your View, labeling them\n**Play** and **Stop** . Open `ViewController.h` and add these methods, which\nwill be mapped to the buttons: \n\n```objective-c\n- (IBAction)playVideo:(id)sender;\n- (IBAction)stopVideo:(id)sender;\n```\n\nNow open `ViewController.m` and define these two functions: \n\n```objective-c\n- (IBAction)playVideo:(id)sender {\n [self.playerView playVideo];\n}\n\n- (IBAction)stopVideo:(id)sender {\n [self.playerView stopVideo];\n}\n```\n\nMost of the IFrame Player API functions have Objective-C equivalents, though some of the\nnaming may differ slightly to more closely match Objective-C coding guidelines. Notable\nexceptions are methods controlling the volume of the video, since these are controlled by\nthe phone hardware or with built in `UIView` instances designed for this purpose,\nsuch as [`MPVolumeView`](https://developer.apple.com/library/ios/documentation/mediaplayer/reference/MPVolumeView_Class/Reference/Reference.html).\n\nOpen your storyboard or Interface Builder and control-drag to connect the **Play** and\n**Stop** buttons to the `playVideo:` and `stopVideo:` methods.\n\nNow build and run the application. Once the video thumbnail loads, you should be able to\nplay and stop the video using native controls in addition to the player controls.\n\nHandle player callbacks\n-----------------------\n\nIt can be useful to programmatically handle playback events, such as playback state changes\nand playback errors. In the JavaScript API, this is done with\n[event listeners](https://developers.google.com/youtube/iframe_api_reference#Adding_event_listener).\nIn Objective-C,this is done with a\n[delegate](https://developer.apple.com/library/ios/documentation/general/conceptual/CocoaEncyclopedia/DelegatesandDataSources/DelegatesandDataSources.html).\n\n\nThe following code shows how to update the interface declaration in\n`ViewController.h` so the class conforms to the delegate protocol. Change\n`ViewController.h`'s interface declaration as follows: \n\n```objective-c\n@interface ViewController : UIViewController\u003cYTPlayerViewDelegate\u003e\n```\n\n`YTPlayerViewDelegate` is a protocol for handling playback events in the player.\nTo update `ViewController.m` to handle some of the events, you first need to set\nthe `ViewController` instance as the delegate of the `YTPlayerView`\ninstance. To make this change, add the following line to the `viewDidLoad` method\nin `ViewController.h`. \n\n```objective-c\nself.playerView.delegate = self;\n```\n\nNow add the following method to `ViewController.m`: \n\n```objective-c\n- (void)playerView:(YTPlayerView *)playerView didChangeToState:(YTPlayerState)state {\n switch (state) {\n case kYTPlayerStatePlaying:\n NSLog(@\"Started playback\");\n break;\n case kYTPlayerStatePaused:\n NSLog(@\"Paused playback\");\n break;\n default:\n break;\n }\n}\n```\n\nBuild and run the application. Watch the log output in Xcode as the player state changes.\nYou should see updates when the video is played or stopped.\n\nThe library provides the constants that begin with the `kYT*` prefix for\nconvenience and readability. For a full list of these constants, look at\n`YTPlayerView.m`.\n\nBest practices and limitations\n------------------------------\n\nThe library builds on top of the IFrame Player API by creating a `WebView` and\nrendering the HTML and JavaScript required for a basic player. The library's goal is to be\nas easy-to-use as possible, bundling methods that developers frequently have to write into a\npackage. There are a few limitations that should be noted:\n\n- The library does not support concurrent video playback in multiple `YTPlayerView` instances. If your application has multiple `YTPlayerView` instances, a recommended best practice is to pause or stop playback in any existing instances before starting playback in a different instance. In the example application that ships with the project, the ViewControllers make use of `NSNotificationCenter` to dispatch notifications that playback is about to begin. Other ViewControllers are notified and will pause playback in their `YTPlayerView` instances.\n- Reuse your existing, loaded `YTPlayerView` instances when possible. When a video needs to be changed in a View, don't create a new `UIView` instance or a new `YTPlayerView` instance, and don't call either `loadVideoId:` or `loadPlaylistId:`. Instead, use the `cueVideoById:startSeconds:` family of functions, which do not reload the `WebView`. There is a noticeable delay when loading the entire IFrame player.\n- This player cannot play private videos, but it can play [unlisted videos](https://support.google.com/youtube/answer/157177). Since this library wraps the existing iframe player, the player's behavior should be nearly identical to that of a player embedded on a webpage in a mobile browser.\n\nContributions\n-------------\n\nSince this is an open-source project, please submit fixes and improvements to the\n[master branch of the GitHub\nproject](https://github.com/youtube/youtube-ios-player-helper)."]]