2

I use NSURLProtocol to add custom header to all requests going out of UIWebview. In this WebView on doing certain operation AJAX call is fired to display a message.This operation to show message uses AJAX, and always times out when i use NSURLProtocol method.It works fine without NSURLProtocol.

Let me know if more info is needed.Here is my code.

+ (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;
}
Aditya Gaonkar
  • 660
  • 6
  • 13

1 Answers1

0

try to implemented this method

-(NSURLRequest *)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response{
[self.client URLProtocol:self wasRedirectedToRequest:request redirectResponse:response];
return request;
}
John Shaw
  • 21
  • 1
  • This did not work for me. Finally web developers agreed to make AJAX asynchronous. I believe that is the correct way of doing this. However, i tried running NSURLConnection on main thread explicitly and it worked for some unknown reason even though AJAX is synchronous. – Aditya Gaonkar Dec 25 '15 at 08:22