2013-04-20 73 views
0

我試圖從我的服務器使用AFNetworking下載自定義文件類型 - 出於某種原因,它說它成功下載了文件,但它看起來像結果已損壞。AFNetworking下載自定義文件

這是我在日誌中得到:

2013-04-20 11:17:40.326 app[18083:907] start downloads 
2013-04-20 11:17:40.392 app[18083:907] Sent 283280 of 283280 bytes, /var/mobile/Applications/187878BC-9D5A-4E1C-9EE4-34512D93BF68/Documents/theprice.cm 
2013-04-20 11:17:40.393 app[18083:907] Successfully downloaded file to /var/mobile/Applications/187878BC-9D5A-4E1C-9EE4-34512D93BF68/Documents/theprice.cm 

我的網絡連接速度快,但它肯定沒有在0.04秒下載283280個字節。

這裏是我的AFNetworking代碼:

NSLog(@"start downloads"); 

NSString *urlpath = [NSString stringWithFormat:@"http://www.domain.com/ygp6bcckll8mw62.cm"]; 
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlpath]]; 

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

[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { 
    NSLog(@"Successfully downloaded file to %@", path); 
} failure:^(AFHTTPRequestOperation *operation, NSError *error) { 
    NSLog(@"Error: %@", error); 
}]; 

[operation setDownloadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) { 
    NSLog(@"Sent %lld of %lld bytes, %@", totalBytesWritten, totalBytesExpectedToWrite, path); 
}]; 

[operation start]; 

當我嘗試訪問該文件的內容,正如人們所預料:它是空的。

有關爲什麼這不正確下載自定義文件類型的任何想法? (.cm)我是否遺漏了AFNetworking代碼中的某些內容以使其行爲異常?

回答

0

你確定outputStream正在被適當的沖洗和關閉?一旦收到所有數據後,AFHTTPRequestOperation可能會將傳輸標記爲已成功完成,但在寫入永久性存儲時沒有任何特別的延遲和/或要求意識。

0

AFNetworking不會向其輸出流發送開放消息。儘管如此,它發送完畢後或發生錯誤時會向其發送close消息。在開始請求之前,您可以嘗試將open發送到輸出流,這將有所幫助。

否則會發出警告,AFNetworking不會檢查流中潛在的失敗代碼,也不能保證所有接收到的字節都已經完全寫入流中。