2015-05-29 32 views
5

我得到的錯誤報告顯示,我的iOS應用在緩慢連接上無法上傳圖像。雖然我的超時時間可能不夠長,但還有另一個問題。NSURLSession,上傳任務 - 獲取傳輸的實際字節數

我發現上傳進度很快就達到了100%,儘管我在查爾斯看到該字節仍在傳輸。我用NSURLSession的方法如下:

- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request 
            fromData:(NSData *)bodyData 
          completionHandler:(void (^)(NSData *data, 
                 NSURLResponse *response, 
                 NSError *error))completionHandler 

,並實現以下的委託方法來接收進度事件:

- (void)URLSession:(NSURLSession *)session 
       task:(NSURLSessionTask *)task 
    didSendBodyData:(int64_t)bytesSent 
    totalBytesSent:(int64_t)totalBytesSent 
totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend 

其實我使用AFNetworking 2.5.2,使用這種方法。我的理論是這個委託方法報告從手機發送的字節,而不是實際傳輸的字節。

以非常低的連接發送300kb將立即發送5-6包,並在等待接收它們時報告100%的進度。

是否有可能獲得已確認傳輸的實際字節數的進度事件?

回答

1

是的,這是可能的!

[operation setUploadProgressBlock:^(NSInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) { 
    float prog = (totalBytesWritten/(totalBytesExpectedToWrite * 1.0f) * 100); 
    [self.progBar setProgress:prog]; 
    NSLog(@"%f%% Uploaded", (totalBytesWritten/(totalBytesExpectedToWrite * 1.0f) * 100)); 

    }]; 
+0

我假設'operation'是一個'AFHTTPRequestOperation'。恐怕,這與使用會話的上述方法具有相同的「缺陷」。 –

+0

如果您正在以正確的方式進行上傳操作,則不會產生任何問題。我使用相同的操作上傳了30張圖片,並跟蹤了答案中提到的進度。確保你使用的是「multipart」。 – Vizllx

+0

您是否嘗試過使用像Charles這樣的代理應用程序來限制上傳速度30 kpbs?正如上面的問題所描述的那樣,這是進展開始異常起作用的時候 –