2014-02-01 5 views
2

Я пытаюсь загрузить файл с сервера, используя afnetworking from iPad.Ожидаемый байт AFNetworking для чтения: -1

Я могу успешно скачать файл. Но, как ни странно, мой totalBytesExpectedToRead всегда равен -1, хотя totalBytesRead правильный. Где я совершил ошибку?

[operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) 
{ 
} 

Весь код здесь.

-(void)fileDownload : (NSString *)pathToDownload : (NSString *)fileExt 
{ 
    hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES]; 
    hud.mode = MBProgressHUDModeAnnularDeterminate; 
    [email protected]"Downloading..."; 

    NSLog(@"fileDownload and pathToDownload is %@",pathToDownload); 

    NSArray *parts = [pathToDownload componentsSeparatedByString:@"\\"]; 
    NSString *fileName = [NSString stringWithFormat:@"%@",[parts objectAtIndex:[parts count]-1]]; 

    if([fileExt isEqualToString:@"pdf"]) 
    { 
     fileNameForAllThreeFile=[fileName stringByDeletingPathExtension]; 
    } 

    NSLog(@"fileName is %@",fileName); 

    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@",IP_ADDRESS,download_recording]]; 

    AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url]; 
    [httpClient setAuthorizationHeaderWithUsername:usernameForAuth password:passwordForAuth]; 

    NSDictionary *parameters = [NSDictionary dictionaryWithObjectsAndKeys:        
          pathToDownload,@"file", 
          nil]; 
    NSMutableURLRequest *request = [httpClient requestWithMethod:@"POST" path:download_recording parameters:parameters]; 

    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request]; 
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *path = [[paths objectAtIndex:0] stringByAppendingPathComponent:fileName]; 
    operation.outputStream = [NSOutputStream outputStreamToFileAtPath:path append:NO]; 

    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) 
    { 
     NSString *responseStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding]; 
     NSLog(@"Request Successful in fileDownload, response '%@'", responseStr); 

     NSLog(@"Successfully downloaded file to %@", path); 
     [self messageDisplay:@"File download complete" :[NSString stringWithFormat:@"%@ download is now complete.",fileName]]; 
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) 
    { 
     NSLog(@"Error in retrieveFromCustomServer: %@", error.localizedDescription); 
     [self performSelectorInBackground:@selector(hideHUDInBackground) withObject:nil]; 

    }]; 
    [operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) 
    { 
     //do something in this line with the calculation to cell 
     // float progress = (float)totalBytesRead/totalBytesExpectedToRead; 
     NSLog(@"Downloaded %lld of %lld bytes", totalBytesRead, totalBytesExpectedToRead); 
     float perCent = totalBytesRead/(float)totalBytesExpectedToRead; 
     hud.progress = perCent ; 
     NSLog(@"Percent is %d and in float is %f",(int)(perCent *100),perCent); 
    }]; 
    [operation start]; 
} 
+1

Да, это значение только получает значение, если сервер возвращает соответствующий заголовок. Если вы управляете сервером, добавьте заголовок 'Content-Length'. –

ответ

5

totalBytesExpectedToRead равен -1, если водосборник Content-Length HTTP не предусмотрен сервер. См. RFC 2616, section 14.13.

Вы должны либо добавить этот заголовок на свой сервер, либо обработать -1, указав UIActivityIndicator вместо UIProgressView.

Или, в вашем случае, используя MBProgressHUD:

hud.mode = MBProgressHUDModeIndeterminate; 
+0

Спасибо. Теперь все в порядке. Я добавил Content-Length. –

Смежные вопросы