【发布时间】:2010-07-20 12:51:53
【问题描述】:
基本上发生的事情是,我需要在我的应用程序中下载一大堆文件,并且我设置了一个队列,使用 NSURLConnection 下载每个文件,并将服务器响应增量存储在 NSMutableData 中,直到下载完成完成,然后将整个内容写入磁盘。
以下是相关部分:
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)_response {
response = [_response retain];
if([response expectedContentLength] < 1) {
data = [[NSMutableData alloc] init];
}
else {
data = [[NSMutableData dataWithCapacity:[response expectedContentLength]] retain];
}
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)_data {
[data appendData:_data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(@"saved: %@", self.savePath);
[data writeToFile:self.savePath atomically:YES];
}
关于为什么这会非常慢的任何见解?模拟器非常糟糕,在实际设备上变得更糟。我的最大下载大小约为 2 兆字节,所以我认为将整个内容存储在内存中直到它完成并不是一个坏主意。这最多可以达到大约 20KB/s(使用直接的 ad-hoc wifi 连接)。
编辑:在我所有的测试用例中,我确实得到了一个 Content-Length 标头,所以这不是随着收到的每一位响应而增加 NSMutableData 的问题。
编辑 2:this 是 Shark 给我的全部。
编辑 3:这就是我设置连接的方式
NSMutableURLRequest *request = [[NSMutableURLRequest requestWithURL:[NSURL URLWithString:[@"http://xxx.xxx.xxx.xxx/index.php?service=" stringByAppendingString:service]]] retain];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:[[options JSONRepresentation] dataUsingEncoding:NSUTF8StringEncoding]];
NSURLConnection *conn = [NSURLConnection connectionWithRequest:request delegate:self];
[conn start];
当然,我实际上并没有硬编码的 url,并且 request 和 conn 都是下载器类的实例变量。没关系,但对于 JSON,我使用的是http://code.google.com/p/json-framework/。选项和服务是方法参数(NSString 和 NSDictionary),它们也不重要。
【问题讨论】:
标签: cocoa-touch ipad nsurlconnection