NSURLProtocol canInitWithRequest:仅适用于某些请求

Gar*_*ett 5 iphone macos objective-c ios

我有一个WebView,我想拦截和修改来自不同站点的某些请求.我对每个截获的请求进行完全相同的修改,无论它来自哪个站点.由于看似没有理由,它适用于除了一个以外的每个站点.这是我的代码:

在我的ResourceLoadDelegate中

- (NSURLRequest *)webView:(WebView *)sender resource:(id)identifier willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)redirectResponse fromDataSource:(WebDataSource *)dataSource
{
    //predicates
    const NSPredicate *site1Predicate = [NSPredicate predicateWithFormat:@"SELF like \"/*predicate1*/""];
    const NSPredicate *site2Predicate = [NSPredicate predicateWithFormat:@"SELF like \"/*predicate2*/""];
    const NSPredicate *site3Predicate = [NSPredicate predicateWithFormat:@"SELF like \"/*predicate3*/""];
    const NSPredicate *site4Predicate = [NSPredicate predicateWithFormat:@"SELF like \"/*predicate4*/""];
    const NSPredicate *site5Predicate = [NSPredicate predicateWithFormat:@"SELF like \"/*predicate5*/""];

    //predicate arrays
    const NSArray *songPredicates = [NSArray arrayWithObjects:site1Predicate, site2Predicate, site3Predicate, site4Predicate, site5Predicate, nil];

    //site is an int with its defined in an enum
    if ([[songPredicates objectAtIndex:site-1] evaluateWithObject:request.URL.host])
    {
        NSMutableURLRequest* newRequest = [request mutableCopy];
        [InterceptionProtocol setProperty:self forKey:@"MyApp" inRequest:newRequest];
        dispatch_async( dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            /* Do stuff */
        });
        return newRequest;
    }
    return request;
}
Run Code Online (Sandbox Code Playgroud)

在InterceptionProtocol.m中

+ (BOOL) canInitWithRequest:(NSURLRequest*)request
{
    id delegate = [NSURLProtocol propertyForKey:@"MyApp" inRequest:request];
    if (delegate) NSLog(@"Can init: %@", request);
    return (delegate != nil);
}
Run Code Online (Sandbox Code Playgroud)

出于某种原因,除了站点4之外,这对于除了站点4之外的所有内容都非常有效.我已经完成了代码并且我知道谓词正确匹配.我不知道这对其他网站有什么用,但不是这个.有任何想法吗?

编辑

完整的源代码可以在这里找到:http: //github.com/garrett-davidson/iLikeMusic

Nas*_*nov 1

看来问题出在predicate4不匹配上site4。您关于单步执行代码及其正确匹配的注释令人困惑 - 如果是这种情况,一切都会正常工作,不是吗?

是否可能是您根据谓词手动测试了您期望的 url - 但在实际运行过程中获得的结果却略有不同(比如由于 URL 编码 - 存在空格或或/?编码+%。放在NSLog前面evaluateWithObject:看看到底进来了什么request.URL.host