2013-04-02 65 views
0

我必須編寫代碼才能從網站上下載,然後以每秒3字節/秒的速度計算下載的吞吐量。我怎樣才能做到這一點? 假設我下載網站,但我需要將它存儲在某種可變數組中,該數組存儲字節,然後在每3秒後將其長度除以3。我可以使用什麼計時器來幫助我瞭解吞吐量?下載一個頁面並計算吞吐量Objective-C

此外,數據需要以字節存儲,以便我可以使用哪種數組類型?

回答

1

請閱讀NSURLConnection。如果您實施的是delegate,則會在收到數據時收到回電。 NSURLConnection提供了一次性創建請求的方法,但這種方式可以將部分結果呈現給用戶。

創建三個屬性來保持狀態:

@property(nonatomic, strong) NSDate *start; 
@property(nonatomic, assign) NSInteger bytesSoFar; 
@property(nonatomic, assign) float throughputSoFar; 

- (void)start { 
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.google.com/"]]; 
    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self]; 
} 

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { 
    self.start = [NSDate date]; 
} 

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { 
    NSDate *now = [NSDate date]; 
    self.bytesSoFar += [data length]; 
    self.throughputSoFar = self.bytesSoFar/[now timeIntervalSinceDate:self.start]; 
    // update the UI with progress 
} 

當你connectionDidFinishLoading,self.throughputSoFar將是最終的吞吐量。

2

閱讀URL Loading System Programming Guide瞭解NSURLConnection。如果您只想計算「吞吐量」的簡單定義,您甚至不需要存儲收到的實際字節數,儘管NSURLConnection會這樣做。你只需要計算收到的字節數。

要測量接收文件所需的時間,請在啓動NSURLConnection之前(或之後)撥打[NSDate timeIntervalSinceReferenceDate]。然後在連接完成後再次調用它。減去。區別在於下載時間以秒爲單位。

閱讀Timer Programming Topics瞭解NSTimer。用一個來通知你三秒鐘過去了。