Je me demande dans quelles conditions un objet NSHTTPURLResponse n'aura pas de clé @ "Content-Length"? Est-il normal/normal de ne pas avoir cette clé?`[[response allHeaderFields] objectForKey: @" Content-Length "]` est-il nul?
J'essaie quelque chose avec le SDK de Dropbox et je me suis rendu compte que
[[response allHeaderFields] objectForKey:@"Content-Length"]
retours nil
et est à l'origine downloadProgress
être infinie:
NSInteger contentLength = [[[response allHeaderFields] objectForKey:@"Content-Length"] intValue];
downloadProgress = (CGFloat)bytesDownloaded/(CGFloat)contentLength;
Est-il possible que je puisse faire la réponse avoir cette clé?
BTW: C'est la réponse que je reçois
(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;
}
EDIT (travail-arounded):
Comme l'a dit @Mitchell. Les serveurs ne renvoient pas toujours une telle clé. (Serveurs étranges de DropBox, pour .png oui, pour les fichiers txt parfois pas: /) Ainsi, afin de calculer le downloadProgress d'un fichier que j'ai modifié (arounded travail) la source:
//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];
}
}
Et depuis J'ai la taille d'un fichier à partir des métadonnées que je peux faire:
- (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
}
De la documentation, nous pouvons voir qu'il ya une méthode qui expectedContentLength de peut retourner NSURLResponseUnknownLength si la longueur ne peut être déterminée. Avez-vous essayé cela? –
Il semble également que vous affectez NSInteger contentLength à la valeur du pointeur de NSNumber, car vous ne pouvez pas stocker les types primitifs dans NSDictionary. Changez cela en NSNumber *. –