2011-01-29 78 views
2

我想計算文件上傳到Dropbox的速度。從上傳百分比獲取上傳速度

下面是我目前使用的代碼:

int numberOfCalls = 0; 

- (float)getUploadSpeed:(float)currentAmountUploaded { 
    numberOfCalls++; 
    NSLog(@"called %d times.", numberOfCalls); 
    NSLog(@"speed approx. %fKB/sec.", (currentAmountUploaded/numberOfCalls)*1024); 
    return (currentAmountUploaded/numberOfCalls)*1024; 
} 

- (void)startUploadSpeedTest:(NSNumber *)uploadCurrent { 

    float uploadedFileSize = [uploadCurrent floatValue]; 

    NSMethodSignature *signature = [[self class] instanceMethodSignatureForSelector:@selector(getUploadSpeed:)]; 

    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; 
    NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature]; 
    [invocation setSelector:@selector(getUploadSpeed:)]; 

    [invocation setTarget:self]; 
    [invocation setArgument:&uploadedFileSize atIndex:2]; 
    [invocation invoke]; 

    NSRunLoop *runLoop = [NSRunLoop currentRunLoop]; 

    [[NSTimer timerWithTimeInterval:1.0 invocation:invocation repeats:YES] retain]; 

    [runLoop run]; 
    [pool release]; 
} 

- (void)restClient:(DBRestClient *)client uploadProgress:(CGFloat)progress forFile:(NSString *)destPath from:(NSString *)srcPath { 
    NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:srcPath error:nil]; 
    float fileSize = ((float)[fileAttributes fileSize]/1024/1024); 
    float uploadedFileSize = fileSize * progress; 

    NSNumber *number = [[[NSNumber alloc] initWithFloat:uploadedFileSize] autorelease]; 

    NSThread *timerThread = [[[NSThread alloc] initWithTarget:self selector:@selector(startUploadSpeedTest:) object:number] autorelease]; 
    [timerThread start]; 
} 

但是,計時器不叫每一秒,我不知道這是獲得速度的最佳方式。

任何幫助表示讚賞。

回答

4

爲什麼不直接在uploadProgress-Method中計算速度?

這是一個非常簡單的解決方案。

-(void) restClient:(DBRestClient *)client uploadProgress:(CGFloat)progress forFile:(NSString *)destPath from:(NSString *)srcPath { 
    static NSDate* date = nil; 
    static double oldUploadedFileSize = 0; 
    if (!date) { 
     date = [[NSDate date] retain]; 
    } else { 
     NSTimeInterval sec = -[date timeIntervalSinceNow]; 
     [date release]; 
     date = [[NSDate date] retain]; 
     NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:srcPath error:nil]; 
     double uploadedFileSize = (double)[fileAttributes fileSize] * progress; 
     if (sec) { 
      NSLog(@"speed approx. %.2f KB/s", (uploadedFileSize - oldUploadedFileSize)/1024.0/sec); 
     } 
     oldUploadedFileSize = uploadedFileSize; 
    } 

} 

注意,第一個和最後一個速度值可能不準確。

+0

非常感謝!無法想出一個方法來使其工作! – 2011-01-29 12:04:12