The media manager is responsible for managing multimedia resources such as files, images, videos, and audio in messages, including upload and download operations.
Files, images, videos, audio and other multimedia resources in messages are all managed through the media manager
This documentation only covers core methods. For more details, check the [WKSDK shared].mediaManager interface in the code.
Custom Upload
Create Upload Task
Inherit from WKMessageFileUploadTask and implement necessary methods:
// Inherit from WKMessageFileUploadTask
@interface WKFileUploadTask : WKMessageFileUploadTask
@end
Implement Upload Task
// Implement four methods: initWithMessage, resume, cancel, suspend
@implementation WKFileUploadTask
- (instancetype)initWithMessage:(WKMessage *)message {
self = [super initWithMessage:message];
if(self) {
[self initTask];
}
return self;
}
- (void)initTask {
// Initialize upload task
// Set up network request, configure parameters, etc.
}
- (void)resume {
// Start or resume upload
[self startUpload];
}
- (void)cancel {
// Cancel upload
[self cancelUpload];
}
- (void)suspend {
// Pause upload
[self pauseUpload];
}
- (void)startUpload {
// Implement actual upload logic
// Example using NSURLSession
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:nil];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"your-upload-url"]];
request.HTTPMethod = @"POST";
// Set up multipart form data
NSString *boundary = @"----WebKitFormBoundary7MA4YWxkTrZu0gW";
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
[request setValue:contentType forHTTPHeaderField:@"Content-Type"];
NSMutableData *body = [NSMutableData data];
// Add file data to body
NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:request fromData:body];
[uploadTask resume];
}
// NSURLSessionDelegate methods
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didSendBodyData:(int64_t)bytesSent totalBytesSent:(int64_t)totalBytesSent totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend {
// Update upload progress
float progress = (float)totalBytesSent / (float)totalBytesExpectedToSend;
dispatch_async(dispatch_get_main_queue(), ^{
[self updateProgress:progress];
});
}
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {
if (error) {
// Upload failed
[self uploadFailedWithError:error];
} else {
// Upload successful
[self uploadCompleted];
}
}
@end
Register Upload Task
// Register custom upload task
[[WKSDK shared].mediaManager addFileUploadTask:[WKFileUploadTask class] contentType:WKContentTypeImage];
Custom Download
Create Download Task
@interface WKFileDownloadTask : WKMessageFileDownloadTask
@end
@implementation WKFileDownloadTask
- (instancetype)initWithMessage:(WKMessage *)message {
self = [super initWithMessage:message];
if(self) {
[self initTask];
}
return self;
}
- (void)initTask {
// Initialize download task
}
- (void)resume {
// Start or resume download
[self startDownload];
}
- (void)cancel {
// Cancel download
[self cancelDownload];
}
- (void)suspend {
// Pause download
[self pauseDownload];
}
- (void)startDownload {
// Implement download logic
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:nil];
NSURL *downloadURL = [NSURL URLWithString:@"file-download-url"];
NSURLSessionDownloadTask *downloadTask = [session downloadTaskWithURL:downloadURL];
[downloadTask resume];
}
// NSURLSessionDownloadDelegate methods
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite {
// Update download progress
float progress = (float)totalBytesWritten / (float)totalBytesExpectedToWrite;
dispatch_async(dispatch_get_main_queue(), ^{
[self updateProgress:progress];
});
}
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location {
// Download completed, move file to final location
NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
NSString *filePath = [documentsPath stringByAppendingPathComponent:@"downloaded_file"];
NSError *error;
[[NSFileManager defaultManager] moveItemAtURL:location toURL:[NSURL fileURLWithPath:filePath] error:&error];
if (!error) {
[self downloadCompletedWithPath:filePath];
} else {
[self downloadFailedWithError:error];
}
}
@end
Register Download Task
// Register custom download task
[[WKSDK shared].mediaManager addFileDownloadTask:[WKFileDownloadTask class] contentType:WKContentTypeImage];
Progress Management
Monitor Upload Progress
// Listen for upload progress
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(onUploadProgress:)
name:@"WKMessageUploadProgressNotification"
object:nil];
- (void)onUploadProgress:(NSNotification *)notification {
WKMessage *message = notification.userInfo[@"message"];
NSNumber *progress = notification.userInfo[@"progress"];
NSLog(@"Upload progress: %.2f%% for message: %@", progress.floatValue * 100, message.messageID);
}
Monitor Download Progress
// Listen for download progress
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(onDownloadProgress:)
name:@"WKMessageDownloadProgressNotification"
object:nil];
- (void)onDownloadProgress:(NSNotification *)notification {
WKMessage *message = notification.userInfo[@"message"];
NSNumber *progress = notification.userInfo[@"progress"];
NSLog(@"Download progress: %.2f%% for message: %@", progress.floatValue * 100, message.messageID);
}
File Management
Get File Path
// Get local file path for message
WKMessage *message = // Your message object
NSString *filePath = [[WKSDK shared].mediaManager getFilePathForMessage:message];
if (filePath && [[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
// File exists locally
NSLog(@"File path: %@", filePath);
} else {
// File needs to be downloaded
[[WKSDK shared].mediaManager downloadFileForMessage:message];
}
Clear Cache
// Clear all media cache
[[WKSDK shared].mediaManager clearAllCache];
// Clear cache for specific message type
[[WKSDK shared].mediaManager clearCacheForContentType:WKContentTypeImage];
// Clear cache older than specified days
[[WKSDK shared].mediaManager clearCacheOlderThanDays:7];
Best Practices
- Progress Feedback: Always provide progress feedback for long-running operations
- Error Handling: Implement proper error handling for network failures
- Cache Management: Regularly clean up old cached files to save storage space
- Background Tasks: Use background tasks for large file uploads/downloads
- Network Optimization: Implement retry logic and adaptive quality based on network conditions
- Security: Validate file types and sizes before processing