我在UIWebView
的实施中遇到了一个问题,即我必须在所有传出的网址请求中添加?app=1
。就是当我在LoadRequest
中使用http://google.com进行webView
时,它应该将其转换为http://google.com?app=1 ...同样如果它是http://google.com/index.php那么它应该将其更改为http://google.com/index.php?app=1
我已经完成了this但是无法获得解决方案..
任何帮助都会很棒..
提前致谢
答案 0 :(得分:1)
我认为你需要类似下面的内容
-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
NSString *url=request.URL.absoluteString;
NSRange extraParam=[url rangeOfString:@"app=1"];
if(extraParam.location == NSNotFound){
url=[url stringByAppendingString:@"?app=1"];
NSURLRequest *newRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:url]];
[webView loadRequest:newRequest];
}
return YES;
}
虽然以上代码未经过测试,但请尝试使用,如果有效的话。
注意 - 这只是一个想法,而不是解决方案。
干杯。
答案 1 :(得分:1)
如果您只想将app=1
添加到初始请求中,然后再将其传递给loadRequest:
,那么只需执行
// Based on we don't know what is after http://www.google.com
// there could be other parameters that we aren't aware of.
NSString *urlStr = @"http://www.google.com....";
// Lets search for '?' to see if there are any parameters set already
if([urlStr rangeOfString:@"?"].location == NSNotFound) {
// There are no parameters already set so we are good and we can just add ours.
urlStr = [urlStr stringByAppendingString:@"?app=1"];
} else {
// The request already has some parameters so we want to be adding ours as an additional param
urlStr = [urlStr stringByAppendingString:@"&app=1"];
}
// Now that we have added our parameter to the request string we can make create the request.
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlStr]];
[webView loadRequest:request];
如果您想将其附加到每个请求,请尝试在webView:shouldStartLoadWithRequest:navigationType:
中执行上述操作(以及一些小修改),如下所示
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
NSString *urlRequestStr = [[request URL] absoluteString];
// We need to make sure that we haven't already been passed a request with app=1 on it.
if([urlRequestStr rangeOfString:@"app=1"].location == NSNotFound) {
// Lets search for '?' to see if there are any parameters set already
if([urlRequestStr rangeOfString:@"?"].location == NSNotFound) {
// There are no parameters already set so we are good and we can just add ours.
urlRequestStr = [urlRequestStr stringByAppendingString:@"?app=1"];
} else {
// The request already has some parameters so we want to be adding ours as an additional param
urlRequestStr = [urlRequestStr stringByAppendingString:@"&app=1"];
}
// Now that we have added our parameter to the request string we can make create the request.
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlRequestStr]];
[webView loadRequest:request];
}
// Continue as normal
return YES;
}
如果有人认为适合对此进行downvote,我会注意到这是经过测试的代码并且可以按照用户的要求运行。因此,如果您认为适合downvote,请留下您认为这值得投票的原因