views:

39

answers:

1

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];

}
A: 

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 following UIWebViewDelegate methods:

- (void)webViewDidStartLoad:(UIWebView *)webView;
- (void)webViewDidFinishLoad:(UIWebView *)webView;
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error;

You could use NSDate for this timestamp (calling [NSDate date]), using the time(3) function, etc. Taking the difference of the two timestamps gives you your interval, i.e. your loading time.

Shaggy Frog