我编写了一个自定义的 NSURLProtocol(称为“memory:”),它允许我根据名称从 NSDictionary 中获取存储的 NSData 项。例如,这段代码注册了 NSURLProtocol 类并添加了一些数据:
[VPMemoryURLProtocol register];
[VPMemoryURLProtocol addData:data withName:@"video"];
这使我可以通过“memory://video”之类的 url 引用 NSData。
下面是我的自定义 NSURLProtocol 实现:
NSMutableDictionary* gMemoryMap = nil;
@implementation VPMemoryURLProtocol
{
}
+ (void)register
{
static BOOL inited = NO;
if (!inited)
{
[NSURLProtocol registerClass:[VPMemoryURLProtocol class]];
inited = YES;
}
}
+ (void)addData:(NSData *)data withName:(NSString *)name
{
if (!gMemoryMap)
{
gMemoryMap = [NSMutableDictionary new];
}
gMemoryMap[name] = data;
}
+ (BOOL)canInitWithRequest:(NSURLRequest *)request
{
NSLog(@"URL: %@, Scheme: %@",
[[request URL] absoluteString],
[[request URL] scheme]);
NSString* theScheme = [[request URL] scheme];
return [theScheme caseInsensitiveCompare:@"memory"] == NSOrderedSame;
}
+ (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request
{
return request;
}
- (void)startLoading
{
NSString* name = [[self.request URL] path];
NSData* data = gMemoryMap[name];
NSURLResponse* response = [[NSURLResponse alloc] initWithURL:[self.request URL]
MIMEType:@"video/mp4"
expectedContentLength:-1
textEncodingName:nil];
id<NSURLProtocolClient> client = [self client];
[client URLProtocol:self didReceiveResponse:response
cacheStoragePolicy:NSURLCacheStorageNotAllowed];
[client URLProtocol:self didLoadData:data];
[client URLProtocolDidFinishLoading:self];
}
- (void)stopLoading
{
}
我不确定这段代码是否有效,但这不是我遇到的问题。尽管注册了自定义协议,但当我尝试在此代码中使用 URL 时,永远不会调用 canInitWithRequest::
NSURL* url = [NSURL URLWithString:@"memory://video"];
AVURLAsset* asset = [[AVURLAsset alloc] initWithURL:url options:nil];
AVAssetImageGenerator* imageGen = [AVAssetImageGenerator assetImageGeneratorWithAsset:asset];
CMTime time = CMTimeMakeWithSeconds(0, 600);
NSError* error;
CMTime actualTime;
CGImageRef image = [imageGen copyCGImageAtTime:time
actualTime:&actualTime
error:&error];
UIImage* uiImage = [UIImage imageWithCGImage:image];
CGImageRelease(image);
如果我使用“memory://video”,图像始终为零,但如果我使用“file:///...”,则效果很好。我错过了什么?为什么不调用 canInitWithRequest ?AVFoundation 是否只支持特定的 URL 协议而不支持自定义的?
谢谢