Listening for events in a UIWebView (iOS)

后端 未结 2 1163
猫巷女王i
猫巷女王i 2021-02-06 03:10

I\'m trying to listen for an event (specifically a button click) from a webpage I have opened in a UIWebView in my iOS app. I know that in other languages there are ways to att

2条回答
  •  既然无缘
    2021-02-06 03:54

    Use a custom scheme. When the user taps the button, ping a url with the custom scheme (myScheme://buttonTapped) and either:

    1. Catch this in the webview delegate method shouldStartLoadWithRequest... (ie check if the URL contains your custom scheme) and route it to the appropriate objective c selector. Or

    2. Register a custom URL protocol and set it up to handle your custom URL scheme. Something like the below:

    @implementation MyURLProtocol
    
    + (BOOL)canInitWithRequest:(NSURLRequest *)request
    {
        return [[[request URL] scheme] isEqualToString:@"myScheme"];
    }
    
    + (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request
    {
        return request;
    }
    
    - (void)startLoading
    {
        NSURLRequest * request = [self request];
        id client = [self client];
    
        NSData * data = [NSMutableData dataWithCapacity:0];
        NSHTTPURLResponse * response = [[[NSHTTPURLResponse alloc] initWithURL:[request URL] statusCode:200 HTTPVersion:@"HTTP/1.1" headerFields:nil] autorelease];
        [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
        [client URLProtocol:self didLoadData:data];
        [client URLProtocolDidFinishLoading:self];
    
        [[NSNotificationCenter defaultCenter] postNotificationName:kSchemeNotification object:nil userInfo:payload];
    }
    
    - (void)stopLoading
    {
    
    }
    

提交回复
热议问题