目前我仍在阅读一些关于 NSTimer
的文档和教程。根据我目前的理解,我们调用计时器并给它一个方法,以便它自己重复。然后我想到了一个主意。(我正在处理其他应用程序项目)
我打算做什么
- 实现
UIWebView
- 在
UIWebView
中实现NSTimer
(可能需要 0.5 秒),使用一种方法检查UIWebView
当前 url(绝对字符串),如果不是我指定的内容,它将重定向 url。
我有我要实现的代码,目的是纠正我对 UIWebView
和 NSTimer
的了解,并在我开始工作之前看看它是否合理。 (我仍在阅读文档。所以想了解更多并在开始之前尝试更多)
现在令我困惑的是,我的方法是否与 NSTimer
兼容?在 UIWebView
viewDidLoad
方法中使用 NSTimer
是否合理?应用程序每 0.5 秒不断运行该方法是否会导致内存过载/崩溃?
NSTimer
的示例(如果我错了请纠正我。但是因为我希望只要用户在 UIWebView
中它就永远运行,我会只需要此代码集,不包括 NSRunLoop
)
NSTimer *t = [NSTimer scheduledTimerWithTimeInterval: 2.0
target: self
selector:@selector(onTick:)
userInfo: nil repeats:NO];
-(void)onTick:(NSTimer *)timer {
//do smth
}
EDIT2- @Robert Ryan,这是我正在使用的代码。(当我第一次更改为这个代码时,它正在工作)**(如果我屏蔽了 range2 部分,那么错误域 error-999 停止了。但是 View 仍然没有加载)
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
NSString *currentURL = [[request URL] absoluteString];
NSRange range1= [currentURL rangeOfString:@"news"];
NSRange range2= [currentURL rangeOfString:@"pdf"];
if (range1.location == NSNotFound)
{
NSURL *url = [NSURL URLWithString:@"http://www.imc.jhmi.edu/news.html"];
[webView loadRequest:[NSURLRequest requestWithURL:url]];
return NO; //no to this if its not found.
}
if(range2.location==NSNotFound)
{
NSURL * url = [NSURL URLWithString:@"http://www.imc.jhmi.edu/news.html"];
[webView loadRequest:[NSURLRequest requestWithURL:url]];
return NO; //no to this if its not found
}
return YES; //everything else ok
}
EDIT3 - 如果我将 NSRange range1 和 range2 组合成 1 个语句,那么它会再次工作(希望它在一小时后仍能工作。xD)
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
NSString *currentURL = [[request URL] absoluteString];
NSRange range1= [currentURL rangeOfString:@"news"];
NSRange range2= [currentURL rangeOfString:@"pdf"];
if (range1.location == NSNotFound & range2.location==NSNotFound)
{
NSURL *url = [NSURL URLWithString:@"http://www.imc.jhmi.edu/news.html"];
[webView loadRequest:[NSURLRequest requestWithURL:url]];
return NO;
}
return YES;
}
最佳答案
如果您想要确保用户不会导航到其他 url,您可以添加以下内容
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
if ([[request.URL absoluteString] isEqualToString:@"http://YourAllowableURL1.com"]) {
return YES;
}
if ([[request.URL absoluteString] isEqualToString:@"http://YourAllowableURL2.com"]) {
return YES;
}
return NO;// user will not be able to go to any other urls
}
您还可以指定允许的 URL 列表,并确保仅对这些 URL 返回 YES
关于objective-c - 带有 UIWebView 的 NSTimer - 可行性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11220502/