UIWebView 与服务器端的通过JS交互的事件调用本地代码 其实也就一个方法:
- (NSString *)stringByEvaluatingJavaScriptFromString:(NSString *)script;
也就只有这一个方法可以折腾
例子:
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
//针对左侧的活动列表页处理
NSString *scheme = request.URL.scheme;
BULog(@"request.URL:%@",request.URL);
if (![scheme isEqualToString:@"lfiphone.banme"]) {
return YES;
}
NSString *query = request.URL.query;
NSArray *paramsArray = [query componentsSeparatedByString:@"&"];
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithCapacity:0];
for (NSString *str in paramsArray) {
NSArray *array = [str componentsSeparatedByString:@"="];
id value = nil;
if (array.count==2) {
value = [array objectAtIndex:1];
}else{
value = [NSNull null];
}
[params setObject:value forKey:[array objectAtIndex:0]];
}
if ([params count] == 0) {
if ([request.URL.scheme isEqualToString:@"lfiphone.banme"]) {
NSArray *params = [request.URL.parameterString componentsSeparatedByString:@"="];
if (params.count%2==0 && params.count>=2) {
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:[params objectAtIndex:1], [params objectAtIndex:0],
nil];
NSInteger appID = [[dict objectForKey:@"app_id"] intValue];
[self.activityHM focusWithAppID:appID is_notfocus:0];
}
return NO;
}
}else{
NSString *path = request.URL.path;
if (![path isEqualToString:@"/activity"]) {
return YES;
}
if (![[params objectForKey:@"action"] isKindOfClass:[NSNull class]]) {
if ([[params objectForKey:@"action"] isEqualToString:@"getudid"]) {
[webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"setUDID('%@');", [[UIDevice currentDevice] uniqueIdentifier]]];
}else if ([[params objectForKey:@"action"] isEqualToString:@"myclock"]){
NSInteger activityID = [[params objectForKey:@"id"] intValue];
NSString *jsonStr = [[params objectForKey:@"json"] URLDecodedString];
NSDictionary *json = [jsonStr JSONValue];
[json retain];
BOOL succ = [self handleTimePushWithData:json activityID:activityID];
[webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"setClock(%d);", succ]];
[json release];
}else if ([[params objectForKey:@"action"] isEqualToString:@"cancelclock"]){
NSInteger activityID = [[params objectForKey:@"id"] intValue];
if ([self cancelClockWithID:activityID]) {
[webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"cancelClock(1);"]];
[BUAlertView alertWithMessage:BMLocalizedStringFromTable(@"ActitivyVC_cancelClockSucc")];
}else{
[webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"cancelClock(0);"]];
[BUAlertView alertWithMessage:BMLocalizedStringFromTable(@"ActitivyVC_cancelClockFail")];
}
}
return NO;
}
}
return YES;
}