NSURLProtocol - 未调用startLoading

时间:2015-10-24 13:45:01

标签: ios objective-c nsurlprotocol

自从升级到iOS 9.1后,我的自定义NSURLProtocol将不再调用-(void)startLoading。还有其他人经历过这个吗?

在iOS 8上一切正常......

代码:

@implementation RZCustomProtocol
@dynamic request;

+ (BOOL)canInitWithRequest:(NSURLRequest *)request
{
    if ([request.URL.scheme isEqualToString:@"imsweb"]) {
        NSLog(@"%@", @"YES");
        return YES;
    }
    return NO;
}

+ (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request {
    return request;
}

+ (BOOL)requestIsCacheEquivalent:(NSURLRequest *)a toRequest:(NSURLRequest *)b {
    return [super requestIsCacheEquivalent:a toRequest:b];
}

- (void)startLoading {
    NSLog(@"STARTLOADING: %@", [self.request.URL absoluteString]);
    NSString *filename = [[self.request.URL lastPathComponent] stringByDeletingPathExtension];
    NSLog(@"%@", filename);
    NSString *videoUrl = [[NSBundle mainBundle] pathForResource:filename ofType:@"mp4"];
    NSData *video = [NSData dataWithContentsOfFile:videoUrl];
    NSLog(@"%lu", (unsigned long)video.length);
    NSHTTPURLResponse *response = [[NSHTTPURLResponse alloc] initWithURL:self.request.URL
                                                              statusCode:200 HTTPVersion:nil headerFields:@{
                                                                                                            @"Content-Length": [NSString stringWithFormat:@"%lu", (unsigned long)video.length],
                                                                                                            @"Content-Type": @"video/mp4",
                                                                                                            }];

    [self.client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
    [self.client URLProtocol:self didLoadData:video];
    [self.client URLProtocolDidFinishLoading:self];
}

- (void)stopLoading {
    NSLog(@"STOPLOADING: %@", [self.request.URL absoluteString]);
}

1 个答案:

答案 0 :(得分:1)

我有同样的问题。在我的例子中,我使用JavaScript动态地向页面添加iframe并在其中加载我的自定义协议内容。在iOS 9.1中,WebView拒绝在通过https访问主文档时加载iframe内容,但它在http上工作正常。这看起来像一个新的安全控件,以避免在安全会话中加载不安全的资源。

我使用的修复方法是将我的方案更改为使用https。例如,使用https://imsweb/...代替imsweb://。这有点像黑客,但我能找到最好的解决方案。

类似的东西:

+ (BOOL)canInitWithRequest:(NSURLRequest *)request
{
    if ([request.URL.scheme isEqualToString:@"https"] &&
            [request.URL.host isEqualToString:@"imsweb"]) {
        NSLog(@"%@", @"YES");
        return YES;
    }
    return NO;
}

当然,您需要在startLoading重新构建正确的网址。