在尝试session.dataTaskWithRequest
使用某个函数从URL读取gzip时遇到问题。
服务器端将.gzip
更改为.bin
并存储文件。
我想用.bin
读取文件。但是,网络连接丢失。
但是,将发生The network connection was lost
错误。
你能告诉我如何解决这个问题吗?
服务器端文件名:xxx.bin
(此bin文件是gzip文件。)
以下代码:
NSURLSessionConfiguration *config = [NSURLSessionConfiguration
defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
NSURL *url = [NSURL URLWithString:@"http://...../xxx.bin"];
NSURLSessionDataTask *task = [session dataTaskWithURL: url
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error) {
NSLog(@"error [%@]", [error localizedDescription]);
}
else {
NSLog(@"success");
}
}];
[task resume];
答案 0 :(得分:1)
You can try two steps of codes to download and extract zip files.
//Fetching zip file from server
-(void)dataSyncFileDonload{
NSString *stringURL = [NSString stringWithFormat:@"http://yourzipfilecontainedURL"];
stringURL = [stringURL stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]];
NSURL *url = [NSURL URLWithString:stringURL];
NSData *urlData = [NSData dataWithContentsOfURL:url];
[self extractDownloadedZipFile:urlData];
}
//File Extraction from Zip file
-(void)extractDownloadedZipFile:(NSData *)data {
//If you are using SQlite and storing in local directory for extraction
NSData *outputData = [data gunzippedData];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [paths objectAtIndex:0];
NSString *dataPath = [path stringByAppendingPathComponent:@"myAppDB.sql"];
NSString *dataPath1 = [path stringByAppendingPathComponent:@"myAppDB.sql.gz"];
dataPath = [dataPath stringByStandardizingPath];
[outputData writeToFile:dataPath atomically:YES];
[data writeToFile:dataPath1 atomically:YES];
[self readExtractedFile:dataPath];
}
//Read upzip file
-(void)readExtractedFile:(NSString *)filepath loaderPercent:(float)loaderPercent loaderTo:(float)loaderTo{
NSData *fileData = [NSData dataWithContentsOfFile:filepath];//destinationPath
NSString *fileString = [[NSString alloc] initWithData:fileData encoding:NSASCIIStringEncoding];
NSArray* allLinedStrings = [fileString componentsSeparatedByCharactersInSet: [NSCharacterSet newlineCharacterSet]];
//You can use you data now.
}