Search code examples
javascriptobjective-cuiwebviewnsurlprotocol

Passing data to objective c with POST rather than GET


I have been using the url intercept method to pass data from javascript to objective C by passing the data as url encoded parameters and using NSURLProtocol to intercept the request however I am now wanting to send larger amounts of data like say 10,000 character long strings but this does not seem practical to do in a GET request. Right?

Is there a way for objective c to intercept POST data sent from a UIWebView?
If so do I still use NSURLProtocol and how do I get the POST data?
If not is there some other way I can pass larger amounts of data from the UIWebView to objective c?


Solution

  • When using code like:

    @implementation AppProtocolHandler
    
    + (void)registerSpecialProtocol {
        static BOOL inited = NO;
    
        if (!inited) {
            inited = YES;
            [NSURLProtocol registerClass:[AppProtocolHandler class]];
        }
    }
    
    - (void)handleRequest {
        NSURLRequest *request = [self request];
    
        // null when via app:// but works when via http://
        NSLog(@"[request HTTPBody]: %@", [request HTTPBody]);
    }
    
    + (BOOL)canInitWithRequest:(NSURLRequest *)request {
        return YES;
    }
    
    + (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request {
        return request;
    }
    
    @end
    

    Requests to some protocols (e.g. app://) will result in [request HTTPBody] being null. But if you send through http:// then the [request HTTPBody] will have the request data in an NSData object as expected.

    So your Javascript should look something like:

    $.post("http://test/hello/world", {'data':"foo bar"});
    

    And not something like:

    $.post("app://test/hello/world", {'data':"foo bar"});