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