对于客户端和网页的交互,最近用的比较多。类型比较全,在此总结一下。
1.常用的GET请求方法
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
[[NSURLCache sharedURLCache] removeCachedResponseForRequest:request];
[self.webview loadRequest:request];
2.关系到用户隐私的,使用POST请求
self.url = [NSString stringWithFormat:@"%@%@", API_SERVER, @"/index.php?r=account/my-account"];
NSString *body = [NSString stringWithFormat: @"uid=%@&token=%@", user.uid,user.token];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString: self.url]];
[request setHTTPMethod: @"POST"];
[request setHTTPBody: [body dataUsingEncoding: NSUTF8StringEncoding]];
[self.webview loadRequest: request];
3.获取网页的title
- (void)webViewDidFinishLoad:(UIWebView *)webView{
NSString *title = [webview stringByEvaluatingJavaScriptFromString:@"document.title"];
NSLog(@"title is : %@",title);
}
4.在某些时候,需要和前端进行交流,比方某些时候调用前端的某个方法。
// changeHeight 是方法,后面的是参数。只不过是以json字符串的方式传过去,当前端收到时,再进行一系列的操作。
[self.webview stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"changeHeight({height:'%@' ,type:'up'});",heiString]];
5.下面就是经常用的交互了。
//在这个代理方法中,我们捕获事件。
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationTyp{
if([request.URL.scheme isEqualToString:@"medical"])
{
//medical://api/edit_data?uid=;
if([request.URL.path isEqualToString:@"/edit_data"]){
NSLog(@"编辑个人资料");
UserData *user = [UserManager sharedInstance].currentUser;
[[NSNotificationCenter defaultCenter] postNotificationName:MESSAGE_SHOW_PERSON_INFO object:user.uid];
}
return NO;
}
return YES;
}
在上面,URL.scheme是固定的,和app对于,这个问前端。
//medical://api/edit_data?uid=;
这个就是我们捕获到edit_data事件。
对于uid是多少,我们就对字符串进行一系列的操作来得到,由于在app中,uid是已知的,就没再多求。