如何在 xcode 中显示 NSTimer 的 Web 请求加载时间?
我需要在后台显示一个计时器,以分钟:秒的格式显示网络请求加载时间。当网络请求加载成功时,计时器必须停止。我的代码在这里:
@interface TimerWithWebrequestViewController : UIViewController {
IBOutlet UIWebView *webView;
IBOutlet UILabel *lbl;
int mainInt;
NSTimer *randomMain;
}
@property(nonatomic,retain) UIWebView *webView;
-(void)upDate;
@end
@implementation TimerWithWebrequestViewController
@synthesize webView;
-(void)viewDidLoad
{
NSString *urlAdd = @"http://www.google.com";
NSURL *url = [NSURL URLWithString:urlAdd];
NSURLRequest *reqObj = [NSURLRequest requestWithURL:url];
[webView loadRequest:reqObj];
[self performSelectorInBackground:@selector (upDate) withObject:nil];
}
-(void)upDate
{
mainInt = 0;
randomMain = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(randomMainVoid) userInfo:nil repeats:YES];
}
-(void)randomMainVoid{
mainInt += 1;
lbl.text = [NSString stringWithFormat:@"%d",mainInt];
}
i need to display a timer in the background for the webrequest loading time in the minutes:seconds format.When the webrequest is loaded successfully the timer has to stop.My code is here:
@interface TimerWithWebrequestViewController : UIViewController {
IBOutlet UIWebView *webView;
IBOutlet UILabel *lbl;
int mainInt;
NSTimer *randomMain;
}
@property(nonatomic,retain) UIWebView *webView;
-(void)upDate;
@end
@implementation TimerWithWebrequestViewController
@synthesize webView;
-(void)viewDidLoad
{
NSString *urlAdd = @"http://www.google.com";
NSURL *url = [NSURL URLWithString:urlAdd];
NSURLRequest *reqObj = [NSURLRequest requestWithURL:url];
[webView loadRequest:reqObj];
[self performSelectorInBackground:@selector (upDate) withObject:nil];
}
-(void)upDate
{
mainInt = 0;
randomMain = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(randomMainVoid) userInfo:nil repeats:YES];
}
-(void)randomMainVoid{
mainInt += 1;
lbl.text = [NSString stringWithFormat:@"%d",mainInt];
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
NSTimer
不是适合这项工作的工具,因为该类要求您指定时间间隔。你要做的就是运行一个“秒表”。您可以通过实现以下UIWebViewDelegate
方法在加载开始时和完成时保存时间戳来实现此目的:您可以使用
NSDate
作为此时间戳(调用[NSDate date]
),使用time(3)
函数等。取两个时间戳的差值即可得出您的时间间隔,即加载时间。NSTimer
is not the right tool for this job, since the class requires you to specify a time interval. What you want to do is run a "stopwatch". You can achieve this by saving a time stamp when the load starts and when it finishes by implementing the followingUIWebViewDelegate
methods:You could use
NSDate
for this timestamp (calling[NSDate date]
), using thetime(3)
function, etc. Taking the difference of the two timestamps gives you your interval, i.e. your loading time.