### Initializing DWDownloadModel and Starting Download Source: https://github.com/a1767280/vod_ios_sdk/blob/master/doc/iOS点播SDK开发指南.html This snippet shows how to create a `DWDownloadModel` and start the download process, including handling progress and state updates. ```APIDOC ## Initialize DWDownloadModel and Start Download ### Description This section details how to create a download model, specifying file details and encryption status, and then initiate the download using the `DWDownloadSessionManager`. It also outlines how to handle download progress and state changes. ### Method Objective-C ### Endpoint N/A (Download initiation) ### Parameters #### `DWDownloadModel` Initialization - **`initWithURLString:filePath:responseToken:userId:videoId:`** - Initializer for `DWDownloadModel`. - **`urlString`** (NSString *) - The URL of the video to download. - **`filePath`** (NSString *) - The local path where the file will be saved. - **`responseToken`** (NSString *) - Required if video encryption is enabled; otherwise, `nil`. - **`userId`** (NSString *) - Required if video encryption is enabled; otherwise, `nil`. - **`videoId`** (NSString *) - Required if video encryption is enabled; otherwise, `nil`. **Note on File Extensions:** - If video encryption is **not** enabled: The file extension **must** be `.mp4`. - If video encryption **is** enabled: The file extension **must** be `.pcm`, and `responseToken`, `userId`, `videoId` must be provided. #### `startWithDownloadModel:progress:state:` Method - **`manager`** (`DWDownloadSessionManager` *) - The singleton instance of the download manager. - **`loadModel`** (`DWDownloadModel` *) - The download model to initiate. - **`progress`** (Block) - A block that is called with download progress updates. - **`progress`** (`DWDownloadProgress` *) - Information about the download progress. - **`downloadModel`** (`DWDownloadModel` *) - The `DWDownloadModel` associated with this progress update. - **`state`** (Block) - A block that is called when the download state changes. - **`downloadModel`** (`DWDownloadModel` *) - The `DWDownloadModel` whose state has changed. - **`state`** (`DWDownloadState`) - The new state of the download. - **`filePath`** (NSString *) - The file path for the download. - **`error`** (NSError *) - An error object if the download failed. ### Download States (`DWDownloadState`) - `DWDownloadStateNone`: Not downloaded or deleted. - `DWDownloadStateReadying`: Waiting to download. - `DWDownloadStateRunning`: Downloading. - `DWDownloadStateSuspended`: Download paused. - `DWDownloadStateCompleted`: Download finished. - `DWDownloadStateFailed`: Download failed. ### Request Example ```objectivec // Initialize DWDownloadModel DWDownloadModel *loadModel = [[DWDownloadModel alloc] initWithURLString:urlString filePath:videoPath responseToken:nil userId:nil videoId:nil]; // Start the download [[DWDownloadSessionManager manager] startWithDownloadModel:loadModel progress:^(DWDownloadProgress *progress, DWDownloadModel *downloadModel) { // Handle download progress updates NSLog(@"Download Progress: %@", progress); } state:^(DWDownloadModel *downloadModel, DWDownloadState state, NSString *filePath, NSError *error) { // Handle download state changes switch (state) { case DWDownloadStateCompleted: NSLog(@"Download Completed!"); break; case DWDownloadStateFailed: NSLog(@"Download Failed: %@", error.localizedDescription); break; default: break; } }]; ``` ### Response N/A (This is an initiation method) ``` -------------------------------- ### Initialize and Start Video Download Source: https://github.com/a1767280/vod_ios_sdk/blob/master/doc/iOS点播SDK开发指南.html Initialize the download manager and model, then start the download process with progress and state callbacks. ```objective-c //初始化DWDownloadSessionManager manager是个单例 DWDownloadSessionManager *manager =[DWDownloadSessionManager manager]; //设置 DWDownloadModel 注:若你所下载的 videoId 未启用视频加密功能,则保存的文件扩展名[必须]是 mp4,responseToken userId videoId均为nil 否则无法播放。 若你所下载的 videoId 启用了视频加密功能,则保存的文件扩展名[必须]是 pcm,responseToken userId videoId必须有值 否则无法播放。详情参见Demo。 DWDownloadModel *loadModel =[[DWDownloadModel alloc]initWithURLString:urlString filePath:videoPath responseToken:nil userId:nil videoId:nil]; //开始下载 [manager startWithDownloadModel:loadModel progress:^(DWDownloadProgress *progress,DWDownloadModel *downloadModel) { progress下载的进度 调用DWDownloadUtility 解析相关进度的信息 downloadModel 本次下载的downloadModel } state:^(DWDownloadModel *downloadModel,DWDownloadState state, NSString *filePath, NSError *error) { state 下载状态 如下几种 DWDownloadStateNone, // 未下载 或 下载删除了 DWDownloadStateReadying, // 等待下载 DWDownloadStateRunning, // 正在下载 DWDownloadStateSuspended, // 下载暂停 DWDownloadStateCompleted, // 下载完成 DWDownloadStateFailed // 下载失败 }]; ``` -------------------------------- ### Complete Video Playback Example in Objective-C Source: https://context7.com/a1767280/vod_ios_sdk/llms.txt This Objective-C code demonstrates a full video playback implementation, including DRM setup, player initialization, playback URL retrieval, and lifecycle management. Ensure DWDrmServer is started for encrypted content and call player cleanup methods when the view disappears. ```objective-c @interface VideoPlayerViewController () @property (nonatomic, strong) DWPlayerView *playerView; @property (nonatomic, strong) DWDrmServer *drmServer; @property (nonatomic, strong) NSDictionary *playUrls; @property (nonatomic, assign) NSTimeInterval lastPlayTime; @end @implementation VideoPlayerViewController - (void)viewDidLoad { [super viewDidLoad]; // 启动DRM服务(加密视频需要) self.drmServer = [[DWDrmServer alloc] initWithListenPort:0]; [self.drmServer start]; // 初始化播放器 self.playerView = [[DWPlayerView alloc] initWithFrame:self.view.bounds]; self.playerView.userId = @"YOUR_USER_ID"; self.playerView.key = @"YOUR_API_KEY"; self.playerView.videoId = self.videoId; self.playerView.delegate = self; self.playerView.drmServerPort = self.drmServer.listenPort; self.playerView.timeOutLoad = 20; self.playerView.timeOutBuffer = 20; [self.view addSubview:self.playerView]; // 设置回调 __weak typeof(self) weakSelf = self; self.playerView.failBlock = ^(NSError *error) { NSLog(@"错误: %@", error); }; self.playerView.getPlayUrlsBlock = ^(NSDictionary *playUrls) { weakSelf.playUrls = playUrls; // 检查状态 if ([[playUrls objectForKey:@"status"] integerValue] != 0) { return; } // 获取播放地址 NSArray *qualities = [playUrls objectForKey:@"qualities"]; NSDictionary *quality = [qualities lastObject]; NSString *playUrl = [quality objectForKey:@"playurl"]; // 开始播放 [weakSelf.playerView setURL:[NSURL URLWithString:playUrl] withCustomId:nil]; [weakSelf.playerView play]; }; // 请求播放信息 [self.playerView startRequestPlayInfo]; } - (void)viewWillDisappear:(BOOL)animated { [super viewWillDisappear:animated]; // 保存播放进度 self.lastPlayTime = CMTimeGetSeconds([self.playerView.player currentTime]); [[NSUserDefaults standardUserDefaults] setFloat:self.lastPlayTime forKey:self.videoId]; // 释放资源 [self.playerView removeTimer]; [self.playerView resetPlayer]; [self.drmServer stop]; } #pragma mark - DWVideoPlayerDelegate - (void)videoPlayerIsReadyToPlayVideo:(DWPlayerView *)playerView { // 恢复上次播放位置 float savedTime = [[NSUserDefaults standardUserDefaults] floatForKey:self.videoId]; if (savedTime > 0) { [playerView oldTimeScrub:savedTime]; } } - (void)videoPlayerDidReachEnd:(DWPlayerView *)playerView { // 清除播放记录 [[NSUserDefaults standardUserDefaults] removeObjectForKey:self.videoId]; } - (void)videoPlayer:(DWPlayerView *)playerView timeDidChange:(float)time { // 更新进度UI } - (void)videoPlayer:(DWPlayerView *)playerView didFailWithError:(NSError *)error { // 尝试备用线路 NSDictionary *quality = [[self.playUrls objectForKey:@"qualities"] lastObject]; NSString *spareUrl = [quality objectForKey:@"spareurl"]; [playerView setURL:[NSURL URLWithString:spareUrl] withCustomId:nil]; [playerView play]; } @end ``` -------------------------------- ### Start Download Source: https://github.com/a1767280/vod_ios_sdk/blob/master/doc/iOS点播SDK开发指南.html Details on how to initiate a download using the `DWDownloadSessionManager` and monitor its progress and state. ```APIDOC ## Start Download ### Description Starts the download process for a given `DWDownloadModel` and provides callbacks for progress and state changes. ### Method POST ### Endpoint Not explicitly defined, but uses `DWDownloadSessionManager`. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **downloadModel** (DWDownloadModel) - Required - The model containing download details. ### Request Example ```objectivec [manager startWithDownloadModel:loadModel progress:^(DWDownloadProgress *progress, DWDownloadModel *downloadModel) { // progress: download progress. Call DWDownloadUtility to parse progress information. // downloadModel: the current downloadModel for this download. } state:^(DWDownloadModel *downloadModel, DWDownloadState state, NSString *filePath, NSError *error) { // state: download state, which can be one of the following: // DWDownloadStateNone, // Not downloaded or deleted // DWDownloadStateReadying, // Waiting to download // DWDownloadStateRunning, // Downloading // DWDownloadStateSuspended, // Download paused // DWDownloadStateCompleted, // Download completed // DWDownloadStateFailed // Download failed }]; ``` ### Response None (This is an action to start a download) ### Response Example None ``` -------------------------------- ### Background Download Setup and Initialization Source: https://github.com/a1767280/vod_ios_sdk/blob/master/doc/iOS点播SDK开发指南.html This snippet demonstrates how to configure the SDK for background downloads in your AppDelegate and initialize the DWDownloadSessionManager. ```APIDOC ## Background Download Setup and Initialization ### Description This section covers the necessary steps to enable background downloads and initialize the `DWDownloadSessionManager` within your application's delegate. ### Method Objective-C ### Endpoint N/A (AppDelegate configuration) ### Parameters #### AppDelegate `didFinishLaunchingWithOptions` - **`application`** (UIApplication *) - The application instance. - **`launchOptions`** (NSDictionary *) - Options for launching the application. #### `DWDownloadSessionManager` Configuration - **`allowsCellular`** (BOOL) - Set to `YES` to allow downloads over cellular networks. - **`configureBackroundSession`** - Must be called to enable background download capabilities. ### Request Example ```objectivec // In your AppDelegate.m - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // Allow downloads over cellular networks [DWDownloadSessionManager manager].allowsCellular = YES; // Configure for background downloads (must be called) [[DWDownloadSessionManager manager] configureBackroundSession]; // ... other setup return YES; } ``` ### Response N/A (Configuration method) ``` -------------------------------- ### DWHttpServerProxy Start and Finish Source: https://github.com/a1767280/vod_ios_sdk/blob/master/doc/api/Classes/DWHttpServerProxy.html Methods to start and finish the proxy operations. ```APIDOC ## - start ### Description Starts the proxy operation. ### Method - (void)start ### Discussion Starts the proxy. ### Declared In DWHttpServerProxy.h ## - finish ### Description Finishes the proxy operation. ### Method - (void)finish ### Discussion Finishes the proxy. ### Declared In DWHttpServerProxy.h ``` -------------------------------- ### Initialize and Display DWPlayerView Source: https://github.com/a1767280/vod_ios_sdk/blob/master/doc/iOS点播SDK开发指南.html Create a DWPlayerView instance, set user credentials and video ID, and configure playback URLs. This snippet demonstrates how to start video playback. ```objective-c DWPlayerView *playerView = [[DWPlayerView alloc]initWithFrame:CGRectMake(0,0,ScreenWidth,ScreenHeight/2-50)]; //设置userID key playerView.userId =USERID; playerView.key =APIKEY; //设置视频ID playerView.videoId =@"xxxxxx"; //设置代理 playerView.delegate =self; [self.view addSubview:playerView]; playerView.getPlayUrlsBlock = ^(NSDictionary *playUrls) { //处理返回的播放信息字典 NSDictionary *dic =[[playUrls objectForKey:@"qualities" ] firstObject]; NSURL *playURL =[NSURL URLWithString:[dic objectForKey:@"playurl"]]; //加载音视频资源 [playerView setURL:playURL withCustomId:nil]; //播放 [playerView play]; }; //请求播放信息 [playerView startRequestPlayInfo]; ``` -------------------------------- ### Start Download with Callbacks Source: https://context7.com/a1767280/vod_ios_sdk/llms.txt Initiates a download task using DWDownloadSessionManager. Supports progress and state callbacks for real-time feedback. Ensure DWDownloadModel is properly initialized with URL, file path, and authentication tokens. ```Objective-C DWDownloadSessionManager *manager = [DWDownloadSessionManager manager]; // 创建下载模型 DWDownloadModel *downloadModel = [[DWDownloadModel alloc] initWithURLString:playUrl filePath:savePath responseToken:token userId:userId videoId:videoId]; // 开始下载(带回调) [manager startWithDownloadModel:downloadModel progress:^(DWDownloadProgress *progress, DWDownloadModel *downloadModel) { // 进度回调 float progressValue = progress.progress; // 下载进度 0-1 float speed = progress.speed; // 下载速度 bytes/s int remainingTime = progress.remainingTime; // 剩余时间 秒 int64_t totalBytes = progress.totalBytesExpectedToWrite; // 文件总大小 int64_t writtenBytes = progress.totalBytesWritten; // 已下载大小 dispatch_async(dispatch_get_main_queue(), ^{ self.progressView.progress = progressValue; self.speedLabel.text = [NSString stringWithFormat:@"%.2f KB/s", speed / 1024]; }); } state:^(DWDownloadModel *downloadModel, DWDownloadState state, NSString *filePath, NSError *error) { // 状态回调 switch (state) { case DWDownloadStateNone: NSLog(@"未下载/已删除"); break; case DWDownloadStateReadying: NSLog(@"等待下载"); break; case DWDownloadStateRunning: NSLog(@"正在下载"); break; case DWDownloadStateSuspended: NSLog(@"下载暂停"); break; case DWDownloadStateCompleted: NSLog(@"下载完成,文件路径: %@", filePath); break; case DWDownloadStateFailed: NSLog(@"下载失败: %@", error.localizedDescription); break; } }]; ``` -------------------------------- ### Start Download Task Source: https://context7.com/a1767280/vod_ios_sdk/llms.txt Initiates a download task using a DWDownloadModel, providing blocks for real-time progress updates and state changes. ```APIDOC ## [METHOD] startWithDownloadModel ### Description Starts a download task with progress and state callbacks. ### Parameters - **downloadModel** (DWDownloadModel) - Required - The model containing URL, path, and metadata. - **progress** (Block) - Required - Callback for progress updates (speed, remaining time, bytes). - **state** (Block) - Required - Callback for download state changes (Running, Completed, Failed, etc.). ``` -------------------------------- ### Start and Manage DWDrmServer for Encrypted Video Playback Source: https://context7.com/a1767280/vod_ios_sdk/llms.txt Initializes and starts the DWDrmServer to handle DRM encryption for video playback. The listen port must be set to the player. ```objective-c // 创建并启动DRM服务 DWDrmServer *drmServer = [[DWDrmServer alloc] initWithListenPort:0]; // 0表示由系统分配端口 if ([drmServer start]) { NSLog(@"DRM服务启动成功,端口: %d", drmServer.listenPort); // 设置播放器DRM端口 self.playerView.drmServerPort = drmServer.listenPort; } else { NSLog(@"DRM服务启动失败"); } // 页面关闭时停止DRM服务 - (void)viewWillDisappear:(BOOL)animated { [super viewWillDisappear:animated]; [self.drmServer stop]; } ``` -------------------------------- ### Initialize Video Advertising Source: https://github.com/a1767280/vod_ios_sdk/blob/master/doc/iOS点播SDK开发指南.html Initialize and start the ad information object using user and video identifiers. ```objective-c DWAdInfo *adInfo = [[DWAdInfo alloc]initWithUserId:USERID andVideoId:videoId type:type]; [adInfo start]; ``` -------------------------------- ### Start Download with DWDownloadSessionManager Source: https://github.com/a1767280/vod_ios_sdk/blob/master/doc/iOS点播SDK开发指南.html Initiate a download using the DWDownloadSessionManager with the configured DWDownloadModel. The progress and state blocks provide feedback on the download's status. ```objective-c [manager startWithDownloadModel:loadModel progress:^(DWDownloadProgress *progress, DWDownloadModel *downloadModel) { progress下载的进度 调用DWDownloadUtility 解析相关进度的信息 downloadModel 本次下载的downloadModel } state:^(DWDownloadModel *downloadModel, DWDownloadState state, NSString *filePath, NSError *error) { state 下载状态 如下几种 DWDownloadStateNone, // 未下载 或 下载删除了 DWDownloadStateReadying, // 等待下载 DWDownloadStateRunning, // 正在下载 DWDownloadStateSuspended, // 下载暂停 DWDownloadStateCompleted, // 下载完成 DWDownloadStateFailed // 下载失败 }]; ``` -------------------------------- ### Initialize and Play Audio Source: https://github.com/a1767280/vod_ios_sdk/blob/master/doc/iOS点播SDK开发指南.html Initializes the DWAudioPlayer, sets the delegate, assigns an audio URL, and starts playback. Ensure the audio URL is correctly formatted. ```objective-c //初始化音频播放器 DWAudioPlayer *audioPlayer =[[DWAudioPlayer alloc]init]; //设置代理 audioPlayer.delegate =self; //设置播放音频URL [audioPlayer setAudioURL:音频URL]; //播放 [audioPlayer audioPlay] ``` -------------------------------- ### Install MJExtension using CocoaPods Source: https://github.com/a1767280/vod_ios_sdk/blob/master/Demo/MJExtension/README.md Use this command to add MJExtension to your project via CocoaPods. ```ruby pod 'MJExtension' ``` -------------------------------- ### Request Download Address and Initialize DWDownloadSessionManager Source: https://github.com/a1767280/vod_ios_sdk/blob/master/doc/iOS点播SDK开发指南.html Initialize DWPlayInfo with user and video details. Set media type and timeout. The finishBlock parses the response to get the download URL. Ensure hlsSupport is set to '0'. ```objective-c //hlsSupport必须传 @“0” DWPlayInfo *playinfo = [[DWPlayInfo alloc] initWithUserId:USERID andVideoId:videoid key:APIKEY hlsSupport:@"0"]; //1为视频 2为音频 0为视频+音频 若不传该参数默认为视频 playinfo.mediatype =@"1"; [playinfo start]; //设置下载HTTP通信超时时间,默认超时时间为10秒,下载过程中HTTP通信超时时,会调用errorBlock下载失败的block,告知你请求资源超时。 playinfo.timeoutSeconds = 20; //请求下载资源成功 返回下载信息 调用DWUtils解析数据 playinfo.finishBlock = ^(NSDictionary *response){ //解析得到下载信息 NSDictionary *playUrls = [DWUtils parsePlayInfoResponse:response]; NSDictionary *dic = [[playUrls objectForKey:@"definitions"] firstObject]; //下载地址字符串 urlString = [dic objectForKey:@"playurl"]; } ``` -------------------------------- ### Configure VR Video Playback Source: https://github.com/a1767280/vod_ios_sdk/blob/master/doc/iOS点播SDK开发指南.html Setup VR configuration and library to render video in a custom view. ```objective-c DWVRConfiguration* config = [DWVRLibrary createConfig]; [config asVideo:playerView.player.currentItem]; [config setContainer:self view:vrView]; [config projectionMode:DWModeProjectionStereoSphere]; [config displayMode:DWModeDisplayNormal]; [config interactiveMode:DWModeInteractiveTouch]; [config pinchEnabled:true]; [config setDirectorFactory:[[CustomDirectorFactory alloc]init]]; self.vrLibrary = [config build]; ``` -------------------------------- ### Retrieve Subtitle Information Source: https://github.com/a1767280/vod_ios_sdk/blob/master/doc/iOS点播SDK开发指南.html Example structure of the dictionary containing subtitle configuration and source URL. ```objective-c subtitleDic = { bottom = "0.23"; code = "utf-8"; color = 0x0000FF; font = "Times New Roman"; size = 42; surroundColor = 0xFF6600; url = "http://1.material.bokecc.com/material/1725A8A9604EAE30/3624.srt"; }; ``` -------------------------------- ### Ad Response JSON Examples Source: https://github.com/a1767280/vod_ios_sdk/blob/master/doc/iOS点播SDK开发指南.html JSON structure for successful and failed ad information retrieval. ```json { "response": { "result": 1, "adid":10 "time": 15, "hasmaterials":1 "canclick":1, "canskip":1, "skiptime":5, "ad": [ { "materialid":100 "material": "http://1.material.bokecc.com/material/1936D297411C3A27/8769.flv", "clickurl": "www.bokecc.com" }, { "materialid":101 "material": "http://1.material.bokecc.com/material/1936D297411C3A27/8771.flv", "clickurl": "www.bokecc.com" } ] } } ``` ```json { "response": { "result": 0, "error": -1, } } ``` -------------------------------- ### DWPlayerView - Request Playback URL and Play Source: https://context7.com/a1767280/vod_ios_sdk/llms.txt Requests video playback information using startRequestPlayInfo, sets the playback URL, and starts playback. ```APIDOC ## DWPlayerView - 获取播放地址并播放 通过startRequestPlayInfo方法请求视频播放信息,在回调中获取播放地址后调用setURL方法设置播放资源,最后调用play方法开始播放。支持错误处理和多清晰度选择。 ### Request Example ```objective-c // 设置回调 playerView.failBlock = ^(NSError *error) { NSLog(@"获取播放信息失败: %@", [error localizedDescription]); }; playerView.getPlayUrlsBlock = ^(NSDictionary *playUrls) { // 检查视频状态 NSNumber *status = [playUrls objectForKey:@"status"]; if (status == nil || [status integerValue] != 0) { NSLog(@"视频不可播放: %@", [playUrls objectForKey:@"statusinfo"]); return; } // 获取清晰度列表 NSArray *qualities = [playUrls objectForKey:@"qualities"]; NSDictionary *selectedQuality = [qualities firstObject]; NSString *playUrl = [selectedQuality objectForKey:@"playurl"]; // 设置播放地址并播放 // customId: 用户自定义参数,用于统计,无需求传nil [playerView setURL:[NSURL URLWithString:playUrl] withCustomId:nil]; [playerView play]; }; // 开始请求播放信息 [playerView startRequestPlayInfo]; ``` ``` -------------------------------- ### DWHttpServerProxy Properties Source: https://github.com/a1767280/vod_ios_sdk/blob/master/doc/api/Classes/DWHttpServerProxy.html Properties for configuring timeout, HTTP range start, and local DRM file offset. ```APIDOC ## timeoutSeconds ### Description Sets the HTTP request timeout in seconds. Defaults to 10 seconds. ### Property `@property (assign, nonatomic) NSTimeInterval timeoutSeconds` ### Discussion Sets the HTTP request timeout in seconds. Defaults to 10 seconds. ### Declared In DWHttpServerProxy.h ## httpRequestRangeStart ### Description Represents the start and end of a range, e.g., [start, end]. ### Property `@property (assign, nonatomic) UInt64 httpRequestRangeStart` ### Discussion Represents the start and end of a range, e.g., [start, end]. ### Declared In DWHttpServerProxy.m ## localDrmFileExtraOffset ### Description Represents the extra file offset of the PCM file relative to the MP4 file. ### Property `@property (assign, nonatomic) off_t localDrmFileExtraOffset` ### Discussion Represents the extra file offset of the PCM file relative to the MP4 file. ### Declared In DWHttpServerProxy.m ``` -------------------------------- ### DWHttpServerConnection Lifecycle Methods Source: https://github.com/a1767280/vod_ios_sdk/blob/master/doc/api/Classes/DWHttpServerConnection.html Methods to control the lifecycle of the HTTP server connection, including starting and finishing the connection. ```APIDOC ## - start ### Description Starts processing the connection. ### Method - (void)start ### Declared In DWHttpServerConnection.h ## - finish ### Description Terminates the connection and releases resources. ### Method - (void)finish ### Declared In DWHttpServerConnection.h ``` -------------------------------- ### Get Media Duration Source: https://github.com/a1767280/vod_ios_sdk/blob/master/doc/iOS点播SDK开发指南.html Retrieves the duration of a media file using its URL string. ```objective-c - (CGFloat)getMediaDurationWithMediaUrl:(NSString *)mediaUrlStr; ``` -------------------------------- ### Initialize Player View Source: https://github.com/a1767280/vod_ios_sdk/blob/master/doc/iOS点播SDK开发指南.html Instructions for initializing and configuring the `DWPlayerView` for video playback. ```APIDOC ## Initialize Player View ### Description Initializes and configures the `DWPlayerView` for video playback, including setting dimensions, timeout, media type, and fill mode. ### Method POST (Implied, as it involves creating and configuring a view) ### Endpoint Not explicitly defined. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```objectivec DWPlayerView *playerView = [[DWPlayerView alloc] initWithframe:CGRectMake(0,0,ScreenWidth,ScreenHeight/2-50)]; // Set HTTP communication timeout for playback requests. playerView.timeoutSeconds = 20; // 1 for video, 2 for audio, 0 for video+audio. Defaults to video if not provided. playerView.mediatype = @"0"; /** Set fill mode. If you want to customize playerView height, change fill mode first. AVPlayerLayer's videoGravity property setting: AVLayerVideoGravityResize, // Non-uniform mode. Fills the entire view area in both dimensions. AVLayerVideoGravityResizeAspect, // Aspect ratio fill, until one dimension reaches the boundary. AVLayerVideoGravityResizeAspectFill, // Aspect ratio fill, until the entire view area is filled, with potential cropping in one dimension. Fill mode defaults to AVLayerVideoGravityResizeAspect */ playerView.videoGravity = AVLayerVideoGravityResizeAspect; playerView.delegate = self; // Set delegate [self.view addSubview:playerView]; // Add to target view ``` ### Response None (This is an initialization step) ### Response Example None ### Notes Do not remove the playerView during playback (e.g., when switching between full screen and non-full screen), as this may cause a bug with audio playing but no video. ``` -------------------------------- ### Initialize DWDownloadModel Source: https://github.com/a1767280/vod_ios_sdk/blob/master/doc/iOS点播SDK开发指南.html Create a DWDownloadModel instance using the obtained download URL string and the desired file path for saving the download. ```objective-c //urlString:下载地址字符串 filePath:文件下载路径 DWDownloadModel *loadModel =[[DWDownloadModel alloc]initWithURLString:urlString filePath:filePath responseToken:nil userId:nil videoId:nil]; ``` -------------------------------- ### Initialize DWDownloadModel Source: https://github.com/a1767280/vod_ios_sdk/blob/master/doc/iOS点播SDK开发指南.html This section explains how to initialize a `DWDownloadModel` with the obtained download URL and file path. ```APIDOC ## Initialize DWDownloadModel ### Description Initializes a `DWDownloadModel` object, which is used to configure and manage individual download tasks. ### Method POST (Implied, as it involves creating a model for download) ### Endpoint Not explicitly defined. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **urlString** (NSString) - Required - The download URL string. - **filePath** (NSString) - Required - The local path where the file will be saved. - **responseToken** (NSString) - Optional - Token for the response. - **userId** (NSString) - Optional - User ID. - **videoId** (NSString) - Optional - Video ID. ### Request Example ```objectivec // urlString: download URL string, filePath: file download path DWDownloadModel *loadModel = [[DWDownloadModel alloc] initWithURLString:urlString filePath:filePath responseToken:nil userId:nil videoId:nil]; ``` ### Response None (This is an initialization step) ### Response Example None ``` -------------------------------- ### DWPlayerView - Initialization Source: https://context7.com/a1767280/vod_ios_sdk/llms.txt Initializes the DWPlayerView, configures user information, playback parameters, and adds it to the view hierarchy. ```APIDOC ## DWPlayerView - 视频播放器初始化 DWPlayerView是SDK的核心播放组件,封装了AVPlayer,提供视频播放、暂停、seek、清晰度切换、倍速播放等功能。支持在线视频和本地视频播放,可配置超时时间、循环播放、静音等属性,并通过代理方法回调播放状态。 ### Request Example ```objective-c // 初始化播放器 DWPlayerView *playerView = [[DWPlayerView alloc] initWithFrame:CGRectMake(0, 0, screenWidth, 300)]; // 配置用户信息 playerView.userId = @"YOUR_USER_ID"; playerView.key = @"YOUR_API_KEY"; playerView.videoId = @"VIDEO_ID"; // 配置播放参数 playerView.timeoutSeconds = 10; // 请求超时时间 playerView.timeOutLoad = 20; // 视频加载超时时间,默认30秒 playerView.timeOutBuffer = 20; // 缓存超时时间,默认30秒 playerView.looping = NO; // 是否循环播放 playerView.muted = NO; // 是否静音 playerView.mediatype = @"1"; // 1:视频 2:音频 0:视频+音频 // 设置视频填充模式 playerView.videoGravity = AVLayerVideoGravityResizeAspect; // 设置代理 playerView.delegate = self; // 添加到视图 [self.view addSubview:playerView]; ``` ``` -------------------------------- ### Request Download URL and Initialize DWDownloadSessionManager Source: https://github.com/a1767280/vod_ios_sdk/blob/master/doc/iOS点播SDK开发指南.html This section details how to request download URLs and initialize the DWDownloadSessionManager. It includes setting up play info, handling responses, and configuring timeouts. ```APIDOC ## Request Download URL and Initialize DWDownloadSessionManager ### Description This endpoint is used to request download URLs for videos and initialize the `DWDownloadSessionManager`. It involves creating `DWPlayInfo` objects, setting media types, configuring HTTP timeouts, and parsing the response to obtain the download URL. ### Method POST (Implied, as it involves requesting and processing data) ### Endpoint Not explicitly defined, but related to play info retrieval. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```objectivec // hlsSupport must be passed as @"0" DWPlayInfo *playinfo = [[DWPlayInfo alloc] initWithUserId:USERID andVideoId:videoid key:APIKEY hlsSupport:@"0"]; // 1 for video, 2 for audio, 0 for video+audio. Defaults to video if not provided. playinfo.mediatype = @"1"; [playinfo start]; // Set download HTTP communication timeout. Default is 10 seconds. If timeout occurs during download, the errorBlock will be called. playinfo.timeoutSeconds = 20; ``` ### Response #### Success Response (200) - **playUrls** (NSDictionary) - Parsed download information. - **urlString** (NSString) - The download URL string. #### Response Example ```objectivec playinfo.finishBlock = ^(NSDictionary *response){ // Parse download information NSDictionary *playUrls = [DWUtils parsePlayInfoResponse:response]; NSDictionary *dic = [[playUrls objectForKey:@"definitions"] firstObject]; // Download URL string urlString = [dic objectForKey:@"playurl"]; }; DWDownloadSessionManager *manager = [DWDownloadSessionManager manager]; ``` ``` -------------------------------- ### Initialize DWPlayerView Source: https://context7.com/a1767280/vod_ios_sdk/llms.txt Initializes the DWPlayerView with frame, user credentials, video ID, and playback configurations. Set delegate for state callbacks. ```objective-c // Initialize player DWPlayerView *playerView = [[DWPlayerView alloc] initWithFrame:CGRectMake(0, 0, screenWidth, 300)]; // Configure user info playerView.userId = @"YOUR_USER_ID"; playerView.key = @"YOUR_API_KEY"; playerView.videoId = @"VIDEO_ID"; // Configure playback parameters playerView.timeoutSeconds = 10; // Request timeout playerView.timeOutLoad = 20; // Video load timeout, default 30s playerView.timeOutBuffer = 20; // Buffer timeout, default 30s playerView.looping = NO; // Loop playback playerView.muted = NO; // Mute audio playerView.mediatype = @"1"; // 1:Video 2:Audio 0:Video+Audio // Set video gravity playerView.videoGravity = AVLayerVideoGravityResizeAspect; // Set delegate playerView.delegate = self; // Add to view [self.view addSubview:playerView]; ``` -------------------------------- ### DWHttpServerProxy Initialization Source: https://github.com/a1767280/vod_ios_sdk/blob/master/doc/api/Classes/DWHttpServerProxy.html Initializes the DWHttpServerProxy with a given URL request. ```APIDOC ## - initWithRequest: ### Description Initializes the proxy with a provided URL request. ### Method - (id)initWithRequest:(NSURLRequest *)_request_ ### Parameters - **request** (NSURLRequest *) - The request to be sent as the proxy's header. ### Return Value - (id) - The initialized proxy instance. ### Discussion Initializes the proxy. ### Declared In DWHttpServerProxy.h ``` -------------------------------- ### Initialize DWUploader Source: https://github.com/a1767280/vod_ios_sdk/blob/master/doc/iOS点播SDK开发指南.html Initialize the DWUploader with user credentials and video details. This includes setting up progress, success, and failure callbacks for the upload process. ```objective-c //videoTitle不得为空 videoPath音视频文件路径 DWUploader *uploader = [[DWUploader alloc] initWithuserId:USERID andKey:APIKEY uploadVideoTitle:videoTitle videoDescription:videoDescripton videoTag:videoTag videoPath:videoPath notifyURL:nil]; //进度的回调 uploader.progressBlock = ^(float progress, NSInteger totalBytesWritten, NSInteger totalBytesExpectedToWrite) { }; //上传成功的回调 uploader.finishBlock = ^() { }; //上传失败的回调 uploader.failBlock = ^(NSError *error) { }; //开始上传 [uploader start]; ``` -------------------------------- ### Initialize and Upload Video with DWUploader Source: https://context7.com/a1767280/vod_ios_sdk/llms.txt Initializes the DWUploader with necessary parameters and sets up callbacks for progress, completion, and failure. Use this for standard video uploads. ```objective-c // 初始化上传器 DWUploader *uploader = [[DWUploader alloc] initWithUserId:@"YOUR_USER_ID" andKey:@"YOUR_API_KEY" uploadVideoTitle:@"视频标题" videoDescription:@"视频描述" videoTag:@"标签1,标签2" videoPath:localVideoPath notifyURL:@"https://your-callback-url.com"]; // 设置参数 uploader.timeoutSeconds = 60; uploader.iscrop = @"0"; // @"1"裁剪 @"0"不裁剪 // 设置分类(可选) [uploader category:@"CATEGORY_ID"]; // 上传进度回调 uploader.progressBlock = ^(float progress, NSInteger totalBytesWritten, NSInteger totalBytesExpectedToWrite) { dispatch_async(dispatch_get_main_queue(), ^{ self.progressView.progress = progress; self.progressLabel.text = [NSString stringWithFormat:@"%.1f%%", progress * 100]; }); }; // 上传完成回调 uploader.finishBlock = ^{ NSLog(@"上传完成"); }; // 上传失败回调 uploader.failBlock = ^(NSError *error) { NSLog(@"上传失败: %@", error.localizedDescription); }; // 上传暂停回调(网络问题) uploader.pausedBlock = ^(NSError *error) { NSLog(@"上传暂停: %@", error.localizedDescription); }; // 保存上传上下文(用于断线续传) uploader.videoContextForRetryBlock = ^(NSDictionary *videoContext) { [[NSUserDefaults standardUserDefaults] setObject:videoContext forKey:@"uploadContext"]; [[NSUserDefaults standardUserDefaults] synchronize]; }; // 开始上传 [uploader start]; // 暂停上传 [uploader pause]; // 继续上传 [uploader resume]; ``` -------------------------------- ### Filter and Convert Dictionary Values with MJExtension Source: https://github.com/a1767280/vod_ios_sdk/blob/master/Demo/MJExtension/README.md Implement mj_newValueFromOldValue to transform property values during model conversion. This example demonstrates converting date strings to NSDate and replacing nil values with empty strings. ```objc // Book #import "MJExtension.h" @implementation Book - (id)mj_newValueFromOldValue:(id)oldValue property:(MJProperty *)property { if ([property.name isEqualToString:@"publisher"]) { if (oldValue == nil) return @""; } else if (property.type.typeClass == [NSDate class]) { NSDateFormatter *fmt = [[NSDateFormatter alloc] init]; fmt.dateFormat = @"yyyy-MM-dd"; return [fmt dateFromString:oldValue]; } return oldValue; } @end // NSDictionary NSDictionary *dict = @{ @"name" : @"5分钟突破iOS开发", @"publishedTime" : @"2011-09-10" }; // NSDictionary -> Book Book *book = [Book mj_objectWithKeyValues:dict]; // printing NSLog(@"name=%@, publisher=%@, publishedTime=%@", book.name, book.publisher, book.publishedTime); ``` -------------------------------- ### Initialize DWPlayerView Source: https://github.com/a1767280/vod_ios_sdk/blob/master/doc/iOS点播SDK开发指南.html Initialize a DWPlayerView with a specified frame. Configure timeout settings, media type, and video gravity for playback. Assign a delegate and add the player view to the view hierarchy. Avoid removing the player view during playback to prevent audio-visual issues. ```objective-c DWPlayerView *playerView = [[DWPlayerView alloc] initWithframe:CGRectMake(0,0,ScreenWidth,ScreenHeight/2-50)]; // 设置请求播放信息HTTP通信超时时间 playerView.timeoutSeconds = 20; //1为视频 2为音频 0为视频+音频 若不传该参数默认为视频 playerView.mediatype =@"0"; /** 设置填充模式 如果要自定义playerView的高,请先改变填充模式 AVPlayerLayer的videoGravity属性设置 AVLayerVideoGravityResize, // 非均匀模式。两个维度完全填充至整个视图区域 AVLayerVideoGravityResizeAspect, // 等比例填充,直到一个维度到达区域边界 AVLayerVideoGravityResizeAspectFill, // 等比例填充,直到填充满整个视图区域,其中一个维度的部分区域会被裁剪 填充模式默认为AVLayerVideoGravityResizeAspect */ playerView.videoGravity =AVLayerVideoGravityResizeAspect; playerView.delegate =self;//设置代理 [self.view addSubview:playerView];//添加到目标视图 ``` -------------------------------- ### Import MJExtension Header Source: https://github.com/a1767280/vod_ios_sdk/blob/master/Demo/MJExtension/README.md Import the main header file after manually adding the source files to your project. ```objective-c #import "MJExtension.h" ``` -------------------------------- ### Set Timeout Duration Source: https://github.com/a1767280/vod_ios_sdk/blob/master/doc/iOS点播SDK开发指南.html Set the timeout duration for loading and buffering. The default is 30 seconds. For example, setting the loading timeout to 20 seconds will trigger a timeout callback if the video doesn't load within that time, allowing for actions like switching to another playback line. ```APIDOC ## Set Timeout Duration ### Description Configures the timeout durations for video loading and buffering. The default is 30 seconds. ### Method Objective-C ### Endpoint N/A (Property Assignment) ### Parameters #### Properties - **timeOutLoad** (int) - Sets the loading timeout duration in seconds. - **timeOutBuffer** (int) - Sets the buffering timeout duration in seconds. ### Request Example ```objectivec // Set loading timeout to 20 seconds playerView.timeOutLoad = 20; // Set buffering timeout to 20 seconds playerView.timeOutBuffer = 20; ``` ### Response N/A ``` -------------------------------- ### Configure and Initialize DWVRLibrary for VR Video Playback Source: https://context7.com/a1767280/vod_ios_sdk/llms.txt Sets up the DWVRLibrary for VR video playback, including configuring projection, display, and interaction modes. This is used when the video is identified as VR content. ```objective-c // 检查是否为VR视频 NSInteger vrMode = [[playUrls objectForKey:@"vrmode"] integerValue]; if (vrMode == 1) { // 隐藏普通播放器 self.playerView.hidden = YES; // 配置VR库 DWVRConfiguration *config = [DWVRLibrary createConfig]; // 设置视频源 [config asVideo:self.playerView.player.currentItem]; // 设置容器视图 [config setContainer:self view:self.vrContainerView]; // 设置投影模式 [config projectionMode:DWModeProjectionSphere]; // 球体投影 // 设置显示模式 [config displayMode:DWModeDisplayNormal]; // 单屏模式 // [config displayMode:DWModeDisplayGlass]; // 双屏(VR眼镜)模式 // 设置交互模式 [config interactiveMode:DWModeInteractiveMotion]; // 重力感应 // [config interactiveMode:DWModeInteractiveTouch]; // 触摸 // [config interactiveMode:DWModeInteractiveMotionWithTouch]; // 两者结合 // 启用缩放 [config pinchEnabled:YES]; // 构建VR库 self.vrLibrary = [config build]; } // 切换交互模式 [self.vrLibrary switchInteractiveMode:DWModeInteractiveTouch]; DWModeInteractive currentMode = [self.vrLibrary getInteractiveMdoe]; // 切换显示模式 [self.vrLibrary switchDisplayMode:DWModeDisplayGlass]; DWModeDisplay displayMode = [self.vrLibrary getDisplayMdoe]; // 切换投影模式 [self.vrLibrary switchProjectionMode:DWModeProjectionDome180]; DWModeProjection projectionMode = [self.vrLibrary getProjectionMode]; ``` -------------------------------- ### Local Audio/Video Playback Source: https://github.com/a1767280/vod_ios_sdk/blob/master/doc/iOS点播SDK开发指南.html Instructions for playing local audio and video files using the SDK's player components. ```APIDOC ## Local Audio/Video Playback ### Description This section explains how to play local audio and video files using the provided player components. ### Playing Local Audio 1. Get the file path of the local audio file. 2. Create an `NSURL` object from the file path. 3. Set the audio URL to the `DWAudioPlayer` instance. 4. Start playback. ```objectivec // path: Local audio file path NSURL *fileURL = [NSURL fileURLWithPath:path]; [audioPlayer setAudioURL:fileURL]; [audioPlayer audioPlay]; ``` ### Playing Local Video 1. Get the file path of the local video file. 2. Create an `NSURL` object from the file path. 3. Set the video URL to the player view. 4. Start playback. ```objectivec // path: Local video file path NSURL *fileURL = [NSURL fileURLWithPath:path]; [playerView setURL:fileURL withCustomId:nil]; [playerView play]; ``` ``` -------------------------------- ### Set up AVAudioSession for Playback Source: https://github.com/a1767280/vod_ios_sdk/blob/master/doc/iOS点播SDK开发指南.html Configure the global AVAudioSession for playback in your application's delegate. This is essential for audio to play correctly. ```objective-c - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { //设置全局AVAudioSession NSError *categoryError = nil; BOOL success = [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:&categoryError]; if (!success) { NSLog(@ ``` ```objective-c NSError *activeError = nil; success = [[AVAudioSession sharedInstance] setActive:YES error:&activeError]; if (!success) { NSLog(@"Error setting audio session active: %@", activeError); } } ``` -------------------------------- ### DWHttpServerBuffer Initialization and Data Retrieval Source: https://github.com/a1767280/vod_ios_sdk/blob/master/doc/api/Classes/DWHttpServerBuffer.html Methods for initializing the buffer manager and retrieving unused data. ```APIDOC ## - initWithData: ### Description Initializes the buffer manager with provided NSData. ### Parameters - **data** (NSData) - Required - The data to be placed into the buffer manager. ### Response - **instance** (id) - The initialized buffer manager. ## - initWithHttpResponse: ### Description Initializes the buffer manager with an NSHTTPURLResponse. The manager converts the response into a standard HTTP response header, stores it in the data property, and sets the range. ### Parameters - **response** (NSHTTPURLResponse) - Required - The HTTP response to be placed into the buffer manager. ### Response - **instance** (id) - The initialized buffer manager. ## - getRemainBuffer ### Description Retrieves the unused data from the buffer manager. If no data is available, it returns an empty NSData object. ### Response - **data** (NSData) - The remaining unused data in the buffer. ```