【发布时间】:2017-09-14 08:30:39
【问题描述】:
我正在从我自己的 Web 服务下载一个文件 (.json),下载完成后,我需要将内容“解压缩”到本地 SQLlite 数据库中。
我理解 NSURLConnection 在另一个线程上异步下载文件以保持主线程打开。问题是当文件下载开始时,主线程显然会继续做它正在做的事情——在这种情况下,试图将文件的内容加载到数据库中。到这种情况发生时,文件要么不存在,要么存在但尚未完成。
只有在文件实际完全下载并准备好使用后,如何运行将文件内容输入数据库的方法?
-(void)downloadTheFileFrom:(NSString*)url withToken:(NSString*)token
{
NSString *conURL = [NSString stringWithFormat:@"%@/%@", apiURL, url];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:conURL]];
[request setHTTPMethod:@"GET"];
[request addValue:@"application/json" forHTTPHeaderField:(@"content-type")];
[request addValue:token forHTTPHeaderField:(@"X-TOKEN")];
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO];
[conn scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
[conn start];
[self saveJsonToDatabase];
}
将文件保存到数据库的方法:
-(void)saveJsonToDatabase
{
NSString *jsonFileToSave = @"drug.json";
NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
NSError *jsonError = nil;
NSString *jsonFile = [documentsPath stringByAppendingPathComponent:[NSString stringWithFormat:@"/content/formulary/files/%@", jsonFileToSave]];
NSData *jsonData = [NSData dataWithContentsOfFile:jsonFile];
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&jsonError];
NSString *formularyTable = [NSString stringWithFormat:@"formulary_%@", [jsonFileToSave stringByDeletingPathExtension]];
FormularyDBManager *formularyDBManagerInstance = [FormularyDBManager new];
[formularyDBManagerInstance insertInto:formularyTable arrayOfDicts:jsonArray];
}
NSURLConnection 的委托方法:
-(void)connection:(NSURLConnection*)connection didReceiveResponse:(NSURLResponse *)response {
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
NSString *apiUrl = [NSString stringWithFormat:@"%@",[response URL]];
NSArray *pathComponents = [apiUrl pathComponents];
NSString *areaFolder = [pathComponents objectAtIndex:3];
NSString *fileName = [response suggestedFilename];
NSString *fileType = [fileName pathExtension];
NSString *docsfolderPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *folderPath = [docsfolderPath stringByAppendingString:[NSString stringWithFormat:@"/content/%@/%@", areaFolder, contentType]];
BOOL isDir;
NSFileManager *fileManager= [NSFileManager defaultManager];
if(![fileManager fileExistsAtPath:folderPath isDirectory:&isDir])
if(![fileManager createDirectoryAtPath:folderPath withIntermediateDirectories:YES attributes:nil error:NULL])
NSLog(@"FileDownloader - connection - Error: Create folder failed %@", folderPath);
NSString *filePath = [folderPath stringByAppendingPathComponent:fileName];
[[NSFileManager defaultManager] createFileAtPath:filePath contents:nil attributes:nil];
connection.file = [NSFileHandle fileHandleForUpdatingAtPath:filePath];
_currentFile = fileName;
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[connection.file writeData:data];
}
-(NSCachedURLResponse *)connection:(FileURLConnection *)connection willCacheResponse:(NSCachedURLResponse*)cachedResponse {
return nil;
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[connection.file closeFile];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(@"GetData - connection - error - %@", error);
}
【问题讨论】:
标签: objective-c cocoa-touch nsurlconnection