Listening for events in a UIWebView (iOS)

心已入冬 提交于 2019-12-03 03:14:25

You can use the UIWebViewDelegate:

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType

The UIWebViewNavigationType values are :

enum {
  UIWebViewNavigationTypeLinkClicked,
  UIWebViewNavigationTypeFormSubmitted,
  UIWebViewNavigationTypeBackForward,
  UIWebViewNavigationTypeReload,
  UIWebViewNavigationTypeFormResubmitted,
  UIWebViewNavigationTypeOther
};typedef NSUInteger UIWebViewNavigationType;

Can check this and then look at the NSURLRequest to get info about that

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
{

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!