在UIWebView中监听事件(iOS)

我试图从我在iOS应用程序的UIWebView中打开的网页上听一个事件(特别是一个button点击)。 我知道在其他语言中有办法将事件监听器附加到某些Web调用,但是我还没有find在Objective-C中实现的方法。 我也没有find任何人说,这是不能做的,所以我决定我应该问。 我在文档中看到,您可以从Javascript进行Objective-C调用,但是我无法控制要监视的网页。 所以我需要一个解决scheme,允许我完全在Objective-C中监听这个事件。

编辑:如果具体会帮助,我试图让用户在Facebook上做一个wallpost。 我正在UIWebview(http://www.facebook.com/sharer/sharer.php?u=)中加载Facebook共享器页面,并希望监视用户何时单击“共享链接”,以便closuresWeb视图。

谢谢大家的时间!

你可以使用UIWebViewDelegate:

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

UIWebViewNavigationType值是:

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

可以检查这个,然后看看NSURLRequest获取有关的信息

使用自定义scheme。 当用户点击button时,用自定义scheme(myScheme:// buttonTapped)ping一个url,然后:

  1. 在webview委托方法shouldStartLoadWithRequest... (即检查URL是否包含您的自定义scheme)并将其路由到适当的目标cselect器。 要么

  2. 注册一个自定义URL协议,并设置它来处理您的自定义URLscheme。 如下所示:

 @implementation MyURLProtocol

 +(BOOL)canInitWithRequest:(NSURLRequest *)请求
 {
     return [[[request URL] scheme] isEqualToString:@“myScheme”];
 }

 +(NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)请求
 {
    退货要求;
 }

 - (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
 {

 }