2

我使用 NSURLProtocol 为所有从 UIWebview 发出的请求添加自定义标头。在此 WebView 上执行某些操作时,会触发 AJAX 调用以显示消息。显示消息的此操作使用 AJAX,并且在我使用 NSURLProtocol 方法时总是超时。没有 NSURLProtocol 也可以正常工作。

如果需要更多信息,请告诉我。这是我的代码。

+ (BOOL)canInitWithRequest:(NSURLRequest *)request
{
    if ([NSURLProtocol propertyForKey:kUserAgentKey inRequest:request] != nil)
        return NO;

    return YES;
}

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

- (void)startLoading
{
    NSMutableURLRequest *newRequest = [self.request mutableCopy];


     NSString *  customAgent = @"CustomeHeaderValue";
    [newRequest setValue:customAgent forHTTPHeaderField:kUserAgentKey];

    [NSURLProtocol setProperty:@YES forKey:kUserAgentKey inRequest:newRequest];
    self.connection = [NSURLConnection connectionWithRequest:newRequest delegate:self];


}
- (void)stopLoading
{
    [self.connection cancel];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [self.client URLProtocol:self didLoadData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    [self.client URLProtocol:self didFailWithError:error];
    self.connection = nil;
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{`enter code here`

    [self.client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageAllowed];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    [self.client URLProtocolDidFinishLoading:self];
    self.connection = nil;
}

- (NSURLRequest *)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response {
    if (response) {
           [[self client] URLProtocol:self wasRedirectedToRequest:request redirectResponse:response];
    }

    return request;
}
4

1 回答 1

0

尝试实现这个方法

-(NSURLRequest *)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response{
[self.client URLProtocol:self wasRedirectedToRequest:request redirectResponse:response];
return request;
}
于 2015-12-24T03:52:00.257 回答