### `+proxyStart:` — Start the local proxy server Source: https://context7.com/changbadevs/ktvhttpcache/llms.txt Starts the local HTTP proxy server. This method must be called before generating any proxy URLs. It returns YES on success and is safe to call multiple times. ```APIDOC ## `+proxyStart:` — Start the local proxy server ### Description Starts the local HTTP proxy server. Must be called before generating any proxy URLs. Returns `YES` on success. Safe to call multiple times; subsequent calls are no-ops if already running. ### Method Class Method ### Parameters * `error` (NSError **) - Output parameter for any error that occurs during startup. ### Request Example ```objc #import - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { NSError *error = nil; BOOL success = [KTVHTTPCache proxyStart:&error]; if (!success) { NSLog(@"KTVHTTPCache failed to start: %@", error.localizedDescription); // Handle startup failure — fall back to direct URLs } else { NSLog(@"KTVHTTPCache proxy running: %d", [KTVHTTPCache proxyIsRunning]); } return YES; } ``` ### Response #### Success Response (YES) Indicates that the proxy server started successfully. #### Failure Response (NO) Indicates that the proxy server failed to start, with an error provided. ### Error Handling If `proxyStart:` returns NO, the `error` parameter will contain details about the failure. ``` -------------------------------- ### Use KTVHTTPCache with AVPlayer Source: https://github.com/changbadevs/ktvhttpcache/blob/master/README.md Example of integrating KTVHTTPCache with AVPlayer. This involves starting the local proxy server, generating a proxy URL from the original URL, and then creating an AVPlayer instance with the proxy URL. ```objc // 1.Start local proxy server. [KTVHTTPCache proxyStart:&error]; // 2.Generate proxy URL. NSURL *proxyURL = [KTVHTTPCache proxyURLWithOriginalURL:originalURL]; // 3.Create AVPlayer with proxy URL. AVPlayer *player = [AVPlayer playerWithURL:proxyURL]; ``` -------------------------------- ### Enable Log Recording to File Source: https://github.com/changbadevs/ktvhttpcache/blob/master/README.md Enable or disable writing logs to a file. Set to `YES` to start recording logs. ```objc // Write logs to file. [KTVHTTPCache logSetRecordLogEnable:YES]; NSString *logFilePath = [KTVHTTPCache logRecordLogFilePath]; ``` -------------------------------- ### Install KTVHTTPCache with Carthage Source: https://github.com/changbadevs/ktvhttpcache/blob/master/README.md Integrate KTVHTTPCache using Carthage by specifying the version in your Cartfile, running 'carthage update', and then dragging the built frameworks into your Xcode project. ```bash github "ChangbaDevs/KTVHTTPCache" ~> 3.0.0 ``` -------------------------------- ### Install KTVHTTPCache with CocoaPods Source: https://github.com/changbadevs/ktvhttpcache/blob/master/README.md Integrate KTVHTTPCache into your Xcode project using CocoaPods by adding the specified line to your Podfile and running 'pod install'. ```objc pod 'KTVHTTPCache', '~> 3.0.0' ``` -------------------------------- ### Start KTVHTTPCache Proxy Server Source: https://context7.com/changbadevs/ktvhttpcache/llms.txt Initiates the local HTTP proxy server. This must be called before generating any proxy URLs. It's safe to call multiple times; subsequent calls are no-ops if already running. Handles potential startup errors. ```objc #import - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { NSError *error = nil; BOOL success = [KTVHTTPCache proxyStart:&error]; if (!success) { NSLog(@"KTVHTTPCache failed to start: %@", error.localizedDescription); // Handle startup failure — fall back to direct URLs } else { NSLog(@"KTVHTTPCache proxy running: %d", [KTVHTTPCache proxyIsRunning]); } return YES; } ``` -------------------------------- ### URL Mapping for Same Resources Source: https://github.com/changbadevs/ktvhttpcache/blob/master/README.md Use this API to map different URLs that point to the same resource to a single cache entry. This is useful when URLs change dynamically, for example, due to different tokens. ```objc /** * For example: * http://www.xxxx.com/video.mp4?token=1 * and * http://www.xxxx.com/video.mp4?token=2 * Although the URLs are different, they all point to the same file and can be returned in the block * http://www.xxxx.com/video.mp4 * to map to the same cache */ [KTVHTTPCache encodeSetURLConverter:^NSURL *(NSURL *URL) { return URL; }]; ``` -------------------------------- ### Get Completed File URL Source: https://github.com/changbadevs/ktvhttpcache/blob/master/README.md Retrieve the URL for a fully cached file. This is automatically merged into a complete file once it's released by the local server. ```objc // If the URL has been fully cached, it will be automatically merged into a complete file after it is released by the local server. NSURL *fileURL= [KTVHTTPCache cacheCompleteFileURLWithURL:originalURL]; ``` -------------------------------- ### Get Error Information Source: https://github.com/changbadevs/ktvhttpcache/blob/master/README.md Retrieve `NSError` information for a specific URL. This can be used for debugging or logging purposes. ```objc // Get error information for a specified URL. NSError *error = [KTVHTTPCache logErrorForURL:URL]; ``` -------------------------------- ### Get Fully Cached File URL Source: https://context7.com/changbadevs/ktvhttpcache/llms.txt Retrieves the local file URL for a completely cached resource. If the resource is not fully cached, it returns nil, prompting the use of a proxy URL for streaming and caching. ```objc NSURL *originalURL = [NSURL URLWithString:@"https://example.com/audio.mp3"]; NSURL *fileURL = [KTVHTTPCache cacheCompleteFileURLWithURL:originalURL]; if (fileURL) { NSLog(@"Fully cached at: %@", fileURL.path); // Play directly from disk — no network needed AVPlayer *player = [AVPlayer playerWithURL:fileURL]; [player play]; } else { // Not fully cached; use the proxy URL for streaming + caching NSURL *proxyURL = [KTVHTTPCache proxyURLWithOriginalURL:originalURL]; AVPlayer *player = [AVPlayer playerWithURL:proxyURL]; [player play]; } ``` -------------------------------- ### `+cacheCompleteFileURLWithURL:` — Get a fully cached file URL Source: https://context7.com/changbadevs/ktvhttpcache/llms.txt Retrieves the local file URL for a resource that has been completely cached. If the resource is only partially cached or not cached at all, it returns `nil`. ```APIDOC ## `+cacheCompleteFileURLWithURL:` — Get a fully cached file URL ### Description Returns the local file URL of a resource that has been completely cached. Returns `nil` if the resource is only partially cached or not cached at all. ### Method Objective-C Class Method ### Endpoint N/A (Objective-C method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```objc NSURL *originalURL = [NSURL URLWithString:@"https://example.com/audio.mp3"]; NSURL *fileURL = [KTVHTTPCache cacheCompleteFileURLWithURL:originalURL]; if (fileURL) { NSLog(@"Fully cached at: %@", fileURL.path); // Play directly from disk — no network needed AVPlayer *player = [AVPlayer playerWithURL:fileURL]; [player play]; } else { // Not fully cached; use the proxy URL for streaming + caching NSURL *proxyURL = [KTVHTTPCache proxyURLWithOriginalURL:originalURL]; AVPlayer *player = [AVPlayer playerWithURL:proxyURL]; [player play]; } ``` ### Response #### Success Response (File URL) - **fileURL** (NSURL *) - The local file URL if the resource is fully cached, otherwise `nil`. #### Response Example (See Request Example for conditional logic) ``` -------------------------------- ### Delete Cached Data Source: https://context7.com/changbadevs/ktvhttpcache/llms.txt Removes cached data for a specific URL or clears the entire cache. This is useful for freeing up storage space, for example, in response to a low storage warning. ```objc NSURL *URL = [NSURL URLWithString:@"https://example.com/old-video.mp4"]; // Delete a single cached resource [KTVHTTPCache cacheDeleteCacheWithURL:URL]; NSLog(@"Cache for URL deleted"); // Wipe everything (e.g., low storage warning) - (void)applicationDidReceiveMemoryWarning:(UIApplication *)application { [KTVHTTPCache cacheDeleteAllCaches]; NSLog(@"All caches cleared. Used: %lld", [KTVHTTPCache cacheTotalCacheLength]); } ``` -------------------------------- ### Configure Logging with `logSetConsoleLogEnable:` and `logSetRecordLogEnable:` Source: https://context7.com/changbadevs/ktvhttpcache/llms.txt Enable or disable console output and file-based log recording. Both are disabled by default. You can also inject custom log entries. ```objc // Enable during development #ifdef DEBUG [KTVHTTPCache logSetConsoleLogEnable:YES]; [KTVHTTPCache logSetRecordLogEnable:YES]; #endif NSURL *logFileURL = [KTVHTTPCache logRecordLogFileURL]; NSLog(@"Log file: %@", logFileURL.path); // Inject your own log entries [KTVHTTPCache logAddLog:@"[MyApp] Started playback session"]; ``` -------------------------------- ### Activate AirPlay Source: https://github.com/changbadevs/ktvhttpcache/blob/master/README.md Set `bindToLocalhost` to `NO` to allow AirPlay requests. This is necessary because the local server only accepts requests from localhost by default for stability. ```objc // Set bindToLocalhost to NO to activate AirPlay. NSURL *proxyURL = [KTVHTTPCache proxyURLWithOriginalURL:originalURL bindToLocalhost:NO]; ``` -------------------------------- ### Enable Console Logging Source: https://github.com/changbadevs/ktvhttpcache/blob/master/README.md Enable or disable console output for logs. Set to `YES` to see logs in the console. ```objc // Enable console output logs. [KTVHTTPCache logSetConsoleLogEnable:YES]; ``` -------------------------------- ### Activate AirPlay Source: https://github.com/changbadevs/ktvhttpcache/blob/master/README.md Activates AirPlay by setting `bindToLocalhost` to `NO`. Local Server only accepts requests from localhost by default for stability reasons. ```APIDOC ## Activate AirPlay ### Description For stability reasons, Local Server only accepts requests from localhost by default, which causes AirPlay to be inactive by default. This can be changed using the following API. ### Method Objective-C ### Code ```objc // Set bindToLocalhost to NO to activate AirPlay. NSURL *proxyURL = [KTVHTTPCache proxyURLWithOriginalURL:originalURL bindToLocalhost:NO]; ``` ``` -------------------------------- ### Preload HLS Content with KTVHCDataHLSLoader Source: https://github.com/changbadevs/ktvhttpcache/blob/master/README.md Preload HLS content using KTVHCDataHLSLoader. Similar to general resource preloading, this involves creating a request and using the loader's delegate to monitor progress. ```objc // For HLS content. KTVHCDataRequest *request= [[KTVHCDataRequest alloc] initWithURL:URL headers:nil]; KTVHCDataHLSLoader *loader = [KTVHTTPCache cacheHLSLoaderWithRequest:request]; loader.delegate = self; [loader prepare]; ``` -------------------------------- ### `+cacheHLSLoaderWithRequest:` — Preload HLS (m3u8) content Source: https://context7.com/changbadevs/ktvhttpcache/llms.txt Creates a KTVHCDataHLSLoader that fetches and caches an HLS playlist and its media segments. Optional delegate methods allow customizing which URLs are loaded and how loaders are created. ```APIDOC ## `+cacheHLSLoaderWithRequest:` — Preload HLS (m3u8) content ### Description Creates a `KTVHCDataHLSLoader` that fetches and caches an HLS playlist and its media segments. Optional delegate methods allow customizing which URLs are loaded and how loaders are created. ### Method Objective-C Class Method ### Endpoint N/A (SDK Method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```objc // Example usage within an HLSPreloader class - (void)preloadHLS:(NSURL *)m3u8URL { KTVHCDataRequest *request = [[KTVHCDataRequest alloc] initWithURL:m3u8URL headers:nil]; self.hlsLoader = [KTVHTTPCache cacheHLSLoaderWithRequest:request]; self.hlsLoader.delegate = self; [self.hlsLoader prepare]; } ``` ### Response #### Success Response N/A (Asynchronous operation, delegate methods are called) #### Response Example N/A ``` -------------------------------- ### Configure Network Timeout with `downloadSetTimeoutInterval:` Source: https://context7.com/changbadevs/ktvhttpcache/llms.txt Sets the timeout for all network requests made by the framework. Increase this value for slow networks. ```objc // Increase timeout for slow networks [KTVHTTPCache downloadSetTimeoutInterval:60.0]; NSLog(@"Timeout: %.0fs", [KTVHTTPCache downloadTimeoutInterval]); // 60 ``` -------------------------------- ### `+cacheLoaderWithRequest:` — Preload content into cache Source: https://context7.com/changbadevs/ktvhttpcache/llms.txt Creates a KTVHCDataLoader that downloads and caches content for a URL without playing it. Use the KTVHCDataLoaderDelegate to track progress and completion. ```APIDOC ## `+cacheLoaderWithRequest:` — Preload content into cache ### Description Creates a `KTVHCDataLoader` that downloads and caches content for a URL without playing it. Use the `KTVHCDataLoaderDelegate` to track progress and completion. ### Method Objective-C Class Method ### Endpoint N/A (SDK Method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```objc // Example usage within a VideoPreloader class - (void)preloadURL:(NSURL *)URL { // Preload the first 5 MB using a Range header NSDictionary *headers = @{@"Range": @"bytes=0-5242880"}; KTVHCDataRequest *request = [[KTVHCDataRequest alloc] initWithURL:URL headers:headers]; self.loader = [KTVHTTPCache cacheLoaderWithRequest:request]; self.loader.delegate = self; self.loader.object = URL; // Attach context [self.loader prepare]; } ``` ### Response #### Success Response N/A (Asynchronous operation, delegate methods are called) #### Response Example N/A ``` -------------------------------- ### Preload Resources with KTVHCDataLoader Source: https://github.com/changbadevs/ktvhttpcache/blob/master/README.md Initiate resource preloading using KTVHCDataLoader. The preloading range can be controlled via the 'Range' parameter in the Request Header. The delegate receives real-time preload status updates. ```objc // The preloading range can be controlled through the Range parameter in the Request Header. KTVHCDataRequest *request= [[KTVHCDataRequest alloc] initWithURL:URL headers:headers]; KTVHCDataLoader *loader = [KTVHTTPCache cacheLoaderWithRequest:request]; loader.delegate = self; [loader prepare]; ``` -------------------------------- ### Preload Content into Cache with KTVHCDataLoader Source: https://context7.com/changbadevs/ktvhttpcache/llms.txt Use `cacheLoaderWithRequest:` to download and cache content for a URL without playing it. Implement `KTVHCDataLoaderDelegate` to track progress and completion. Attach context using the `object` property. ```Objective-C #import @interface VideoPreloader () @property (nonatomic, strong) KTVHCDataLoader *loader; @end @implementation VideoPreloader - (void)preloadURL:(NSURL *)URL { // Preload the first 5 MB using a Range header NSDictionary *headers = @{@"Range": @"bytes=0-5242880"}; KTVHCDataRequest *request = [[KTVHCDataRequest alloc] initWithURL:URL headers:headers]; self.loader = [KTVHTTPCache cacheLoaderWithRequest:request]; self.loader.delegate = self; self.loader.object = URL; // Attach context [self.loader prepare]; } - (void)ktv_loader:(KTVHCDataLoader *)loader didChangeProgress:(double)progress { NSLog(@"Preload progress: %.1f%%", progress * 100); } - (void)ktv_loaderDidFinish:(KTVHCDataLoader *)loader { NSLog(@"Preload complete for: %@", loader.request.URL); NSLog(@"Loaded bytes: %lld", loader.loadedLength); [loader close]; } - (void)ktv_loader:(KTVHCDataLoader *)loader didFailWithError:(NSError *)error { NSLog(@"Preload failed: %@", error.localizedDescription); [loader close]; } @end ``` -------------------------------- ### Network Configuration Source: https://github.com/changbadevs/ktvhttpcache/blob/master/README.md Configures network settings including download timeout interval and acceptable content types for downloaded resources. ```APIDOC ## Network Configuration ### Description Configures network settings including download timeout interval and acceptable content types for downloaded resources. ### Method Objective-C ### Code ```objc // Set timeout interval. [KTVHTTPCache downloadSetTimeoutInterval:30]; /** * For security/stability considerations, only responses with the following Content-Type are enabled by default: * - text/x * - video/x * - audio/x * - application/x-mpegURL * - vnd.apple.mpegURL * - application/mp4 * - application/octet-stream * - binary/octet-stream * To open more types, use this API setting */ [KTVHTTPCache downloadSetAcceptableContentTypes:contentTypes]; // This handler is triggered when a Content-Type type is not accepted by default. You can decide whether to accept it by yourself. [KTVHTTPCache downloadSetUnacceptableContentTypeDisposer:^BOOL(NSURL *URL, NSString *contentType) { return NO; }]; ``` ``` -------------------------------- ### `+proxyURLWithOriginalURL:` — Generate a proxy URL (localhost only) Source: https://context7.com/changbadevs/ktvhttpcache/llms.txt Converts an original HTTP URL into a local proxy URL. The player uses this URL, and KTVHTTPCache intercepts the request to cache data and forward it. Returns the original URL if it's a file URL or if the proxy is not running. ```APIDOC ## `+proxyURLWithOriginalURL:` — Generate a proxy URL (localhost only) ### Description Converts an original HTTP URL into a local proxy URL. The player uses this URL; KTVHTTPCache intercepts the request, caches data, and forwards it. Returns the original URL unchanged if it is a file URL or the proxy is not running. ### Method Class Method ### Parameters * `originalURL` (NSURL *) - The original URL of the media resource. ### Request Example ```objc NSURL *originalURL = [NSURL URLWithString:@"https://example.com/video.mp4"]; // Start the server first NSError *error = nil; [KTVHTTPCache proxyStart:&error]; NSURL *proxyURL = [KTVHTTPCache proxyURLWithOriginalURL:originalURL]; // proxyURL => http://localhost:PORT//placeholder/video.mp4 AVPlayerItem *item = [AVPlayerItem playerItemWithURL:proxyURL]; AVPlayer *player = [AVPlayer playerWithPlayerItem:item]; [player play]; ``` ### Response * `NSURL` - The generated proxy URL or the original URL if conversion is not possible or applicable. ``` -------------------------------- ### Set Acceptable Content Types Source: https://github.com/changbadevs/ktvhttpcache/blob/master/README.md Specify the Content-Type values that are accepted by default. By default, only specific types like `text/x`, `video/x`, `audio/x`, `application/x-mpegURL`, `vnd.apple.mpegURL`, `application/mp4`, `application/octet-stream`, and `binary/octet-stream` are enabled. Use this API to include additional types. ```objc /** * For security/stability considerations, only responses with the following Content-Type are enabled by default: * - text/x * - video/x * - audio/x * - application/x-mpegURL * - vnd.apple.mpegURL * - application/mp4 * - application/octet-stream * - binary/octet-stream * To open more types, use this API setting */ [KTVHTTPCache downloadSetAcceptableContentTypes:contentTypes]; ``` -------------------------------- ### Set Download Timeout Interval Source: https://github.com/changbadevs/ktvhttpcache/blob/master/README.md Configure the timeout interval for download requests. The default value is not specified, so setting it explicitly is recommended. ```objc // Set timeout interval. [KTVHTTPCache downloadSetTimeoutInterval:30]; ``` -------------------------------- ### Preload HLS (m3u8) Content with KTVHCDataHLSLoader Source: https://context7.com/changbadevs/ktvhttpcache/llms.txt Use `cacheHLSLoaderWithRequest:` to fetch and cache an HLS playlist and its media segments. The `KTVHCDataHLSLoaderDelegate` can be used to customize which URLs are loaded. Return `nil` from `ktv_HLSLoader:makeURLsForContent:` to preload all segments. ```Objective-C #import @interface HLSPreloader () @property (nonatomic, strong) KTVHCDataHLSLoader *hlsLoader; @end @implementation HLSPreloader - (void)preloadHLS:(NSURL *)m3u8URL { KTVHCDataRequest *request = [[KTVHCDataRequest alloc] initWithURL:m3u8URL headers:nil]; self.hlsLoader = [KTVHTTPCache cacheHLSLoaderWithRequest:request]; self.hlsLoader.delegate = self; [self.hlsLoader prepare]; } - (void)ktv_HLSLoader:(KTVHCDataHLSLoader *)loader didChangeProgress:(double)progress { NSLog(@"HLS preload progress: %.1f%%", progress * 100); } - (void)ktv_HLSLoaderDidFinish:(KTVHCDataHLSLoader *)loader { NSLog(@"HLS preload done. Finished: %d", loader.isFinished); [loader close]; } - (void)ktv_HLSLoader:(KTVHCDataHLSLoader *)loader didFailWithError:(NSError *)error { NSLog(@"HLS preload error: %@", error); [loader close]; } // Optional: filter which segment URLs to preload - (NSArray *)ktv_HLSLoader:(KTVHCDataHLSLoader *)loader makeURLsForContent:(NSString *)content { // Return nil to preload all segments; return a subset to limit preloading return nil; } @end ``` -------------------------------- ### Generate Localhost Proxy URL Source: https://context7.com/changbadevs/ktvhttpcache/llms.txt Converts an original HTTP URL into a local proxy URL. The player should use this generated URL. KTVHTTPCache intercepts requests to this URL for caching and forwarding. Returns the original URL if it's a file URL or the proxy is not running. ```objc NSURL *originalURL = [NSURL URLWithString:@"https://example.com/video.mp4"]; // Start the server first NSError *error = nil; [KTVHTTPCache proxyStart:&error]; NSURL *proxyURL = [KTVHTTPCache proxyURLWithOriginalURL:originalURL]; // proxyURL => http://localhost:PORT//placeholder/video.mp4 AVPlayerItem *item = [AVPlayerItem playerItemWithURL:proxyURL]; AVPlayer *player = [AVPlayer playerWithPlayerItem:item]; [player play]; ``` -------------------------------- ### Handle Unacceptable Content Types Source: https://github.com/changbadevs/ktvhttpcache/blob/master/README.md Implement a handler to decide whether to accept responses with Content-Types that are not accepted by default. Returning `YES` will accept the content type, while `NO` will reject it. ```objc // This handler is triggered when a Content-Type type is not accepted by default. You can decide whether to accept it by yourself. [KTVHTTPCache downloadSetUnacceptableContentTypeDisposer:^BOOL(NSURL *URL, NSString *contentType) { return NO; }]; ``` -------------------------------- ### Set Fixed Port for KTVHTTPCache Proxy Source: https://context7.com/changbadevs/ktvhttpcache/llms.txt Sets a specific port for the proxy server to listen on. This must be called before `proxyStart:`. If the server is already running, this call has no effect. The default behavior is to use an ephemeral port. ```objc // Must be called before proxyStart: [KTVHTTPCache proxySetPort:18080]; NSError *error = nil; [KTVHTTPCache proxyStart:&error]; // Server now listens on port 18080 ``` -------------------------------- ### Logging System Source: https://github.com/changbadevs/ktvhttpcache/blob/master/README.md Provides APIs for managing the logging system, including retrieving error information, enabling console logs, and writing logs to a file. ```APIDOC ## Logging system ### Description Provides APIs for managing the logging system, including retrieving error information, enabling console logs, and writing logs to a file. ### Method Objective-C ### Code ```objc // Get error information for a specified URL. NSError *error = [KTVHTTPCache logErrorForURL:URL]; // Enable console output logs. [KTVHTTPCache logSetConsoleLogEnable:YES]; // Write logs to file. [KTVHTTPCache logSetRecordLogEnable:YES]; NSString *logFilePath = [KTVHTTPCache logRecordLogFilePath]; ``` ``` -------------------------------- ### `+logSetConsoleLogEnable:` / `+logSetRecordLogEnable:` — Configure logging Source: https://context7.com/changbadevs/ktvhttpcache/llms.txt Provides options to enable or disable console output and file-based log recording for debugging and monitoring. ```APIDOC ## `+logSetConsoleLogEnable:` / `+logSetRecordLogEnable:` — Configure logging ### Description Enable or disable console output and file-based log recording. Both are `NO` by default. ### Method Objective-C Class Methods ### Parameters #### `+logSetConsoleLogEnable:` - **`enable`** (BOOL) - Set to YES to enable console logging. #### `+logSetRecordLogEnable:` - **`enable`** (BOOL) - Set to YES to enable file-based log recording. ### Code Example ```objc // Enable during development #ifdef DEBUG [KTVHTTPCache logSetConsoleLogEnable:YES]; [KTVHTTPCache logSetRecordLogEnable:YES]; #endif NSURL *logFileURL = [KTVHTTPCache logRecordLogFileURL]; NSLog(@"Log file: %@", logFileURL.path); // Inject your own log entries [KTVHTTPCache logAddLog:@"[MyApp] Started playback session"]; ``` ``` -------------------------------- ### Control HTTP Headers with `downloadSetWhitelistHeaderKeys:` and `downloadSetAdditionalHeaders:` Source: https://context7.com/changbadevs/ktvhttpcache/llms.txt Control which HTTP headers are forwarded to the network or injected into requests. By default, only essential headers are forwarded. Extend the whitelist or inject static headers as needed. ```objc // Allow a custom CDN authentication header to be forwarded [KTVHTTPCache downloadSetWhitelistHeaderKeys:@[ @"User-Agent", @"Connection", @"Accept", @"Accept-Encoding", @"Accept-Language", @"Range", @"X-CDN-Auth" // custom header to pass through ]]; // Inject static headers on every outgoing request [KTVHTTPCache downloadSetAdditionalHeaders:@{ @"User-Agent": @"MyApp/2.0 iOS", @"X-App-Version": @"2.0.0" }]; ``` -------------------------------- ### `+downloadSetTimeoutInterval:` — Configure network timeout Source: https://context7.com/changbadevs/ktvhttpcache/llms.txt Sets the timeout for all network requests made by the framework. This allows for adjustment based on network conditions. ```APIDOC ## `+downloadSetTimeoutInterval:` — Configure network timeout ### Description Sets the timeout for all network requests made by the framework. ### Method Objective-C Class Method ### Parameters #### Arguments - **`interval`** (NSTimeInterval) - The timeout interval in seconds. ### Code Example ```objc // Increase timeout for slow networks [KTVHTTPCache downloadSetTimeoutInterval:60.0]; NSLog(@"Timeout: %.0fs", [KTVHTTPCache downloadTimeoutInterval]); // 60 ``` ``` -------------------------------- ### `+proxySetPort:` — Set a fixed server port Source: https://context7.com/changbadevs/ktvhttpcache/llms.txt Sets a fixed port for the local HTTP proxy server. This must be called before `proxyStart:`. If the server is already running, this method has no effect. ```APIDOC ## `+proxySetPort:` — Set a fixed server port ### Description By default the server binds to an ephemeral port. Use this to pin the server to a specific port before calling `proxyStart:`. Has no effect if the server is already running. ### Method Class Method ### Parameters * `port` (NSInteger) - The desired port number for the proxy server. ### Request Example ```objc // Must be called before proxyStart: [KTVHTTPCache proxySetPort:18080]; NSError *error = nil; [KTVHTTPCache proxyStart:&error]; // Server now listens on port 18080 ``` ``` -------------------------------- ### `+proxyURLWithOriginalURL:bindToLocalhost:` — Generate a proxy URL for AirPlay / LAN Source: https://context7.com/changbadevs/ktvhttpcache/llms.txt Generates a proxy URL similar to `proxyURLWithOriginalURL:`, but allows specifying whether to bind to localhost. When `bindToLocalhost` is NO, the proxy URL uses the device's LAN IP address, which is necessary for AirPlay and other remote playback scenarios. ```APIDOC ## `+proxyURLWithOriginalURL:bindToLocalhost:` — Generate a proxy URL for AirPlay / LAN ### Description Same as `proxyURLWithOriginalURL:` but when `bindToLocalhost:NO`, the proxy URL uses the device's LAN IP address instead of `localhost`. Required for AirPlay and other remote playback scenarios. ### Method Class Method ### Parameters * `originalURL` (NSURL *) - The original URL of the media resource. * `bindToLocalhost` (BOOL) - If NO, the proxy URL will use the device's LAN IP address; otherwise, it uses `localhost`. ### Request Example ```objc NSURL *originalURL = [NSURL URLWithString:@"https://example.com/stream.mp4"]; // bindToLocalhost:NO enables AirPlay NSURL *proxyURL = [KTVHTTPCache proxyURLWithOriginalURL:originalURL bindToLocalhost:NO]; // proxyURL => http://192.168.1.x:PORT//placeholder/stream.mp4 AVPlayerItem *item = [AVPlayerItem playerItemWithURL:proxyURL]; self.player = [AVPlayer playerWithPlayerItem:item]; ``` ### Response * `NSURL` - The generated proxy URL using either localhost or the device's LAN IP address. ``` -------------------------------- ### Preprocess HLS Playlist Content with `hlsSetContentHandler:` Source: https://context7.com/changbadevs/ktvhttpcache/llms.txt Intercepts and modifies raw HLS m3u8 playlist text before caching or serving. Use this to rewrite absolute segment URLs into relative paths for local proxy routing. ```objc [KTVHTTPCache hlsSetContentHandler:^NSString *(NSString *content) { // Rewrite absolute TS segment URLs to relative paths // so the proxy server handles caching each segment NSMutableString *result = [NSMutableString stringWithString:content]; // Example: replace absolute URLs with proxy-routed relative paths [result replaceOccurrencesOfString:@"https://cdn.example.com/segments/" withString:@"./" options:0 range:NSMakeRange(0, result.length)]; return result; }]; ``` -------------------------------- ### Filter by Content-Type with `downloadSetAcceptableContentTypes:` and `downloadSetUnacceptableContentTypeDisposer:` Source: https://context7.com/changbadevs/ktvhttpcache/llms.txt Control which server Content-Type values are accepted for caching. Use the disposer block for dynamic runtime decisions. ```objc // Add application/json to accepted types (in addition to defaults) NSMutableArray *types = [[KTVHTTPCache downloadAcceptableContentTypes] mutableCopy]; [types addObject:@"application/json"]; [KTVHTTPCache downloadSetAcceptableContentTypes:types]; // Dynamically decide whether to accept unknown content types [KTVHTTPCache downloadSetUnacceptableContentTypeDisposer:^BOOL(NSURL *URL, NSString *contentType) { // Accept anything from trusted CDN regardless of content type if ([URL.host hasSuffix:@"trusted-cdn.com"]) { return YES; } NSLog(@"Rejected content type: %@ for URL: %@", contentType, URL); return NO; }]; ``` -------------------------------- ### Generate LAN Proxy URL for AirPlay Source: https://context7.com/changbadevs/ktvhttpcache/llms.txt Generates a proxy URL using the device's LAN IP address instead of `localhost`. This is essential for AirPlay and other remote playback scenarios. The player uses this URL to stream content via the proxy on the local network. ```objc NSURL *originalURL = [NSURL URLWithString:@"https://example.com/stream.mp4"]; // bindToLocalhost:NO enables AirPlay NSURL *proxyURL = [KTVHTTPCache proxyURLWithOriginalURL:originalURL bindToLocalhost:NO]; // proxyURL => http://192.168.1.x:PORT//placeholder/stream.mp4 AVPlayerItem *item = [AVPlayerItem playerItemWithURL:proxyURL]; self.player = [AVPlayer playerWithPlayerItem:item]; ``` -------------------------------- ### Configure Maximum Cache Size Source: https://context7.com/changbadevs/ktvhttpcache/llms.txt Sets the maximum total size for cached data. When this limit is exceeded, the oldest cached data is automatically evicted. The default is 500 MB. ```objc // Set cache limit to 1 GB long long oneGB = 1024LL * 1024 * 1024; [KTVHTTPCache cacheSetMaxCacheLength:oneGB]; NSLog(@"Max cache: %.0f MB", [KTVHTTPCache cacheMaxCacheLength] / 1024.0 / 1024.0); // 1024 MB NSLog(@"Used cache: %.2f MB", [KTVHTTPCache cacheTotalCacheLength] / 1024.0 / 1024.0); ``` -------------------------------- ### Track and Clear Errors with `logErrorForURL:`, `logErrors`, and `logCleanErrorForURL:` Source: https://context7.com/changbadevs/ktvhttpcache/llms.txt Query and clear per-URL errors tracked by the framework. Useful for surfacing caching failures to the user and for debugging. ```objc NSURL *URL = [NSURL URLWithString:@"https://example.com/video.mp4"]; NSError *error = [KTVHTTPCache logErrorForURL:URL]; if (error) { switch (error.code) { case KTVHCErrorCodeResponseContentType: NSLog(@"Rejected content type for %@", URL.host); break; case KTVHCErrorCodeNotEnoughDiskSpace: NSLog(@"Disk full — clearing old caches"); [KTVHTTPCache cacheDeleteAllCaches]; break; case KTVHCErrorCodeResponseStatusCode: NSLog(@"Bad HTTP status from server"); break; default: NSLog(@"Cache error %ld: %@", (long)error.code, error.localizedDescription); } [KTVHTTPCache logCleanErrorForURL:URL]; } // Inspect all errors NSDictionary *allErrors = [KTVHTTPCache logErrors]; NSLog(@"Total URLs with errors: %lu", (unsigned long)allErrors.count); ``` -------------------------------- ### Normalize Dynamic URLs Source: https://context7.com/changbadevs/ktvhttpcache/llms.txt Maps dynamic URL variants to a canonical URL to share the same cache entry. This function is called frequently, so the provided block should be lightweight. It's useful for stripping parameters like tokens and expiry times. ```objc // Strip token and expiry query parameters so all variants share one cache [KTVHTTPCache encodeSetURLConverter:^NSURL *(NSURL *URL) { NSURLComponents *components = [NSURLComponents componentsWithURL:URL resolvingAgainstBaseURL:NO]; NSArray *filtered = [components.queryItems filteredArrayUsingPredicate:[NSPredicate predicateWithBlock: ^BOOL(NSURLQueryItem *item, NSDictionary *bindings) { // Remove ephemeral auth params return ![@["token", "expiry", "sign"] containsObject:item.name]; }] ]; components.queryItems = filtered.count > 0 ? filtered : nil; return components.URL ?: URL; }]; // Now all three map to the same cache entry: // https://cdn.example.com/video.mp4?token=abc&expiry=1234 // https://cdn.example.com/video.mp4?token=xyz&expiry=5678 // https://cdn.example.com/video.mp4 ``` -------------------------------- ### `+downloadSetWhitelistHeaderKeys:` / `+downloadSetAdditionalHeaders:` — Control HTTP headers Source: https://context7.com/changbadevs/ktvhttpcache/llms.txt Allows control over which HTTP headers are forwarded to the network or injected into outgoing requests. ```APIDOC ## `+downloadSetWhitelistHeaderKeys:` / `+downloadSetAdditionalHeaders:` — Control HTTP headers ### Description By default, only specific headers are forwarded. This allows extending the list of forwarded headers or injecting static headers on every outgoing request. ### Method Objective-C Class Methods ### Parameters #### `+downloadSetWhitelistHeaderKeys:` - **`keys`** (NSArray) - An array of header keys to whitelist for forwarding. #### `+downloadSetAdditionalHeaders:` - **`headers`** (NSDictionary) - A dictionary of static headers to inject into outgoing requests. ### Code Example ```objc // Allow a custom CDN authentication header to be forwarded [KTVHTTPCache downloadSetWhitelistHeaderKeys:@[ @"User-Agent", @"Connection", @"Accept", @"Accept-Encoding", @"Accept-Language", @"Range", @"X-CDN-Auth" // custom header to pass through ]]; // Inject static headers on every outgoing request [KTVHTTPCache downloadSetAdditionalHeaders:@{ @"User-Agent": @"MyApp/2.0 iOS", @"X-App-Version": @"2.0.0" }]; ``` ``` -------------------------------- ### `+encodeSetURLConverter:` — Normalize dynamic URLs Source: https://context7.com/changbadevs/ktvhttpcache/llms.txt Maps dynamic URL variants, such as those with different authentication tokens, to a canonical URL to ensure they share the same cache entry. This method should be called with a lightweight block as it may be invoked frequently. ```APIDOC ## `+encodeSetURLConverter:` — Normalize dynamic URLs ### Description Maps dynamic URL variants (e.g., different authentication tokens) to a canonical URL so they share the same cache entry. Called frequently — keep the block lightweight. ### Method Objective-C Class Method ### Endpoint N/A (Objective-C method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```objc // Strip token and expiry query parameters so all variants share one cache [KTVHTTPCache encodeSetURLConverter:^NSURL *(NSURL *URL) { NSURLComponents *components = [NSURLComponents componentsWithURL:URL resolvingAgainstBaseURL:NO]; NSArray *filtered = [components.queryItems filteredArrayUsingPredicate:[NSPredicate predicateWithBlock: ^BOOL(NSURLQueryItem *item, NSDictionary *bindings) { // Remove ephemeral auth params return ![@["token", "expiry", "sign"] containsObject:item.name]; }] ]; components.queryItems = filtered.count > 0 ? filtered : nil; return components.URL ?: URL; }]; // Now all three map to the same cache entry: // https://cdn.example.com/video.mp4?token=abc&expiry=1234 // https://cdn.example.com/video.mp4?token=xyz&expiry=5678 // https://cdn.example.com/video.mp4 ``` ### Response #### Success Response The URL converter is set. Subsequent URL requests will be normalized according to the provided block. #### Response Example (See Request Example for usage and effect) ``` -------------------------------- ### Identify and Decode KTVHTTPCache Proxy URLs Source: https://context7.com/changbadevs/ktvhttpcache/llms.txt Provides functions to determine if a given URL is a KTVHTTPCache proxy URL and to extract the original, unproxied URL from it. Useful for debugging or managing cached resources. ```objc NSURL *url = [NSURL URLWithString:@"http://localhost:18080/https%3A%2F%2Fexample.com%2Fvideo.mp4/placeholder/video.mp4"]; if ([KTVHTTPCache proxyIsProxyURL:url]) { NSURL *original = [KTVHTTPCache proxyOriginalURLWithURL:url]; NSLog(@"Original URL: %@", original); // => https://example.com/video.mp4 } ``` -------------------------------- ### `+proxyIsProxyURL:` / `+proxyOriginalURLWithURL:` — Identify and decode proxy URLs Source: https://context7.com/changbadevs/ktvhttpcache/llms.txt Provides utility methods to determine if a given URL is a KTVHTTPCache proxy URL and to extract the original URL from a proxy URL. ```APIDOC ## `+proxyIsProxyURL:` / `+proxyOriginalURLWithURL:` — Identify and decode proxy URLs ### Description Check whether a URL is a KTVHTTPCache proxy URL, and extract the original URL from it. ### Method Class Methods ### Parameters * `url` (NSURL *) - The URL to check or decode. ### Request Example ```objc NSURL *url = [NSURL URLWithString:@"http://localhost:18080/https%3A%2F%2Fexample.com%2Fvideo.mp4/placeholder/video.mp4"]; if ([KTVHTTPCache proxyIsProxyURL:url]) { NSURL *original = [KTVHTTPCache proxyOriginalURLWithURL:url]; NSLog(@"Original URL: %@", original); // => https://example.com/video.mp4 } ``` ### Response * `proxyIsProxyURL:` returns a BOOL indicating if the URL is a proxy URL. * `proxyOriginalURLWithURL:` returns the original `NSURL` if the input is a proxy URL, otherwise it might return the original URL or nil depending on implementation. ``` -------------------------------- ### URL Mapping Source: https://github.com/changbadevs/ktvhttpcache/blob/master/README.md Maps dynamically changing URLs pointing to the same resource to a single cache entry. This is useful when resource URLs include dynamic parameters like tokens. ```APIDOC ## URL Mapping ### Description If the URL pointing to the same resource changes dynamically, you can use the following API for mapping. ### Method Objective-C ### Code ```objc /** * For example: * http://www.xxxx.com/video.mp4?token=1 * and * http://www.xxxx.com/video.mp4?token=2 * Although the URLs are different, they all point to the same file and can be returned in the block * http://www.xxxx.com/video.mp4 * to map to the same cache */ [KTVHTTPCache encodeSetURLConverter:^NSURL *(NSURL *URL) { return URL; }]; ``` ``` -------------------------------- ### Stop KTVHTTPCache Proxy Server Source: https://context7.com/changbadevs/ktvhttpcache/llms.txt Terminates the local HTTP proxy server, releasing resources. Outstanding connections are closed. After this call, `proxyURLWithOriginalURL:` will return the original URL unchanged. ```objc - (void)applicationDidEnterBackground:(UIApplication *)application { // Optionally stop the proxy to release resources [KTVHTTPCache proxyStop]; NSLog(@"Proxy running: %d", [KTVHTTPCache proxyIsRunning]); // NO } ``` -------------------------------- ### Manage Cached Data Source: https://github.com/changbadevs/ktvhttpcache/blob/master/README.md Retrieves the complete file URL for a given URL if it has been fully cached. The default cache space is 500m, after which an elimination mechanism is enabled. ```APIDOC ## Manage Cached Data ### Description Retrieves the complete file URL for a given URL if it has been fully cached. The default cache space is 500m, after which an elimination mechanism is enabled. ### Method Objective-C ### Code ```objc // If the URL has been fully cached, it will be automatically merged into a complete file after it is released by the local server. NSURL *fileURL= [KTVHTTPCache cacheCompleteFileURLWithURL:originalURL]; ``` ``` -------------------------------- ### `+cacheCacheItemWithURL:` / `+cacheAllCacheItems` — Inspect cache state Source: https://context7.com/changbadevs/ktvhttpcache/llms.txt Allows inspection of cache metadata for a specific URL or enumeration of all cached items. Each `KTVHCDataCacheItem` provides details on total, cached, and valid byte lengths, along with cached byte zones. ```APIDOC ## `+cacheCacheItemWithURL:` / `+cacheAllCacheItems` — Inspect cache state ### Description Retrieve cache metadata for a specific URL or enumerate all cached items. Each `KTVHCDataCacheItem` exposes the total, cached, and valid byte lengths along with the cached byte zones. ### Method Objective-C Class Methods ### Endpoint N/A (Objective-C methods) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```objc NSURL *URL = [NSURL URLWithString:@"https://example.com/video.mp4"]; // Inspect a single item KTVHCDataCacheItem *item = [KTVHTTPCache cacheCacheItemWithURL:URL]; if (item) { NSLog(@"Total length : %lld bytes", item.totalLength); NSLog(@"Cached length : %lld bytes", item.cacheLength); NSLog(@"Valid length : %lld bytes", item.vaildLength); for (KTVHCDataCacheItemZone *zone in item.zones) { NSLog(@" Zone — offset: %lld, length: %lld", zone.offset, zone.length); } } // Enumerate all items NSArray *all = [KTVHTTPCache cacheAllCacheItems]; NSLog(@"Cached URLs: %lu", (unsigned long)all.count); long long total = [KTVHTTPCache cacheTotalCacheLength]; NSLog(@"Total cache usage: %.2f MB", total / 1024.0 / 1024.0); ``` ### Response #### Success Response (Cache Item Data) - **item** (KTVHCDataCacheItem *) - Cache metadata for a specific URL, including `totalLength`, `cacheLength`, `vaildLength`, and `zones`. - **all** (NSArray *) - An array of all cached items. - **total** (long long) - The total cache usage in bytes. #### Response Example (See Request Example for details) ``` -------------------------------- ### `+proxyStop` — Stop the local proxy server Source: https://context7.com/changbadevs/ktvhttpcache/llms.txt Stops the local HTTP proxy server, terminating any outstanding connections. After this call, `proxyURLWithOriginalURL:` will return the original URL unchanged. ```APIDOC ## `+proxyStop` — Stop the local proxy server ### Description Stops the local HTTP proxy server. Outstanding connections are terminated. After calling this, `proxyURLWithOriginalURL:` returns the original URL unchanged. ### Method Class Method ### Request Example ```objc - (void)applicationDidEnterBackground:(UIApplication *)application { // Optionally stop the proxy to release resources [KTVHTTPCache proxyStop]; NSLog(@"Proxy running: %d", [KTVHTTPCache proxyIsRunning]); // NO } ``` ```