1
下面的代码位用于下载由压缩的JSON或压缩的jpg图像组成的数据“包”。问题是图像压缩文件下载。有问题的文件是5 MB,大约需要10分钟才能在64GB的iphone 7上下载,而在模拟器上运行的配置相当慷慨的iMac上大约需要5分钟。使用AFNetworking的下载速度非常慢
接收到的数据将被存储,但在下载完所有文件后才会被处理,因此在下载完成之前,应该没有其他地方发生。
这似乎相当过分,因为我可以在一个可以忽略的时间段内使用网络浏览器下载文件。我看了各种问题和答案,并没有发现任何有用的东西。
任何援助将不胜感激。
-(NSInteger)getPackageData:(NSString *)url type:(NSInteger)isZip fileName:(NSString *)fileName
item:(NSString *)item
{
__block NSInteger errorCode=0;
isReady=0;
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
if(isZip==0){
manager.responseSerializer=[AFJSONResponseSerializer serializer];
}else{
manager.responseSerializer=[AFHTTPResponseSerializer serializer];
}
AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModePublicKey];
[policy setValidatesDomainName:YES];
manager.securityPolicy = policy;
/****************
for self signed certs
manager.securityPolicy.allowInvalidCertificates = YES;
manager.securityPolicy.validatesDomainName = NO;
***************/
NSURL *mURL = [NSURL URLWithString:url];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:mURL];
[request setCachePolicy: NSURLRequestReloadIgnoringLocalCacheData];
[request setTimeoutInterval:100];
NSURLSessionDataTask *dataTask =
[manager dataTaskWithRequest:request
completionHandler:^(NSURLResponse *response,
id json,
NSError *error) {
if (error) {
if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
//error condition 1
NSInteger statusCode = [(NSHTTPURLResponse *) response statusCode];
if(statusCode==403){ // unauthorized
errorCode=-1;
}
}
}
else if(isZip==1){
// process Zipped json Files for data update
NSString *filePath = [jsonPath stringByAppendingPathComponent:fileName];
[json writeToFile:filePath options:NSDataWritingAtomic error:&error];
[[NSNotificationCenter defaultCenter] postNotificationName:@"dataReady" object:item];
errorCode=0;
}else if(isZip==2){ //zipped photos file
NSString *filePath = [photoPath stringByAppendingPathComponent:fileName];
CS_LOG(@"Saving URL %@ to photo file %@",url,filePath);
[json writeToFile:filePath options:NSDataWritingAtomic error:&error];
CLS_LOG(@"Saved");
[[NSNotificationCenter defaultCenter] postNotificationName:@"dataReady" object:@"PHOTOSREADY"];
errorCode=0;
}
} ];
[dataTask resume];
return errorCode;
}
可能不会帮助你,但我会做的第一件事是用“基本”AFNetworking下载任务代码替换你的功能。看看速度如何。如果速度更快,则开始重新添加上面的其他功能,直到遇到影响速度的东西。 – DonMag
@DonMag谢谢 - 我会重写这篇文章,看看会发生什么。无论如何,我很难想到更小的实现。 – jmf1205
嗯......你可能有一个合乎逻辑的理由,但是......一般来说,NSURLSessionDataTask用于小数据位,然后在内存中进行操作,而NSURLSessionDownloadTask用于下载大量数据(例如zip文件)并将其存储在磁盘上。也许你应该使用DownloadTask来处理大的压缩文件,并使用DataTask来处理你的JSON数据。 – DonMag