我不知道NSHTTPURLResponse對象在什麼條件下沒有key @「Content-Length」?沒有那個鑰匙是否正常/正常?`[[allHeaderFields] objectForKey:@「Content-Length」]`是否爲零?
我試圖與Dropbox的SDK的東西,我已經意識到
[[response allHeaderFields] objectForKey:@"Content-Length"]
回報nil
,並導致downloadProgress
是無限的:
NSInteger contentLength = [[[response allHeaderFields] objectForKey:@"Content-Length"] intValue];
downloadProgress = (CGFloat)bytesDownloaded/(CGFloat)contentLength;
有沒有什麼辦法可以使迴應有那個關鍵?
BTW:這是我得到
(gdb) po [response allHeaderFields]
{
"Cache-Control" = "max-age=0";
Connection = "keep-alive";
"Content-Encoding" = gzip;
"Content-Type" = "text/plain; charset=UTF-16LE";
Date = "Wed, 10 Aug 2011 06:21:43 GMT";
Etag = 228n;
Pragma = public;
Server = dbws;
"Transfer-Encoding" = Identity;
}
編輯響應(工作arounded):
正如@Mitchell說。服務器並不總是返回這樣的密鑰。 (奇怪的DropBox的服務器,有時不爲png是,對於TXT文件:/) 因此,爲了計算我修改(工作arounded)的源文件的downloadProgress:
//In DBRequest.m
- (void)connection:(NSURLConnection*)connection didReceiveData:(NSData*)data {
...
bytesDownloaded += [data length];
//start of modification
//Server might not contain @"Content-Length" key,
//in that case use the downloadedBytes. Is better
//than having an infinite value because it could
//be handled by DBRestClient's delegate. (If not
//it will have the same effect as infinite)
if ([response expectedContentLength] == NSURLResponseUnknownLength) {
downloadProgress = (CGFloat)bytesDownloaded;
}else{
NSInteger contentLength = [[[response allHeaderFields] objectForKey:@"Content-Length"] intValue];
downloadProgress = (CGFloat)bytesDownloaded/(CGFloat)contentLength;
}
//end of modification
if (downloadProgressSelector) {
[target performSelector:downloadProgressSelector withObject:self];
}
}
而且,由於我已經從元數據文件的大小,我可以這樣做:
- (void)restClient:(DBRestClient *)client loadProgress:(CGFloat)progress forFile:(NSString *)destPath {
if (progress > 1) {//Work-around: This means the progress is not a
progress = progress/((CGFloat)(metadataOfTheFile.totalBytes));
}
... update the progress bar here
}
從技術文檔,我們可以看到有可能返回NSURLResponseUnknownLength如果長度無法確定的方法expectedContentLength。你嘗試過嗎? –
它也看起來像你從NSNumber的指針值分配NSInteger contentLength,因爲你不能在NSDictionary中存儲基元類型。將其更改爲NSNumber *。 –