首先,我创建了“subjects.sqlite”并将其插入Xcode文件“Copy Bundle Resrources”
我使用了这段代码
NSData *fetchedData = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://www.precaliga.com/iphone/subjects.sqlite"]];
NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *filePath = [documentsPath stringByAppendingPathComponent:@"subjects.sqlite"];
[fetchedData writeToFile:filePath atomically:YES];
NSFileManager *fileMgr = [NSFileManager defaultManager];
BOOL success = [fileMgr fileExistsAtPath:filePath];
if (!success) {
NSLog(@"Cannot locate database file '%@'.", filePath);
}
else {
self.db = [DBController sharedDatabaseController:filePath];
DataTable* table = [_db ExecuteQuery:@"SELECT * FROM subjects"];
NSLog(@"%@",table.columns);
NSLog(@"Downloaded Successfuly ..");
}
但是“table.columns”返回
2013-04-12 11:34:06.202 Precaliga [82123:c07]( )
因为它没有读取下载的sqlite文件。所以我怎样才能在下载功能后读取数据
提前致谢..请帮帮我
答案 0 :(得分:0)
试试这个
NSData *fetchedData = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://www.precaliga.com/iphone/subjects.sqlite"]];
NSLog(@"%d",fetchedData.length);
NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *filePath = [documentsPath stringByAppendingPathComponent:@"subjects.sqlite"];
if (![[NSFileManager defaultManager] fileExistsAtPath:filePath])
[[NSFileManager defaultManager] createFileAtPath:filePath contents:fetchedData attributes:nil];
[fetchedData writeToFile:filePath atomically:YES];
NSFileManager *fileMgr = [NSFileManager defaultManager];
BOOL success = [fileMgr fileExistsAtPath:filePath];
if (!success)
{
NSLog(@"Cannot locate database file '%@'.", filePath);
}
else
{
NSLog(@"Downloaded Successfuly ..");
}
修改强>
在AppDelegate.m
中写下这些内容- (void) copyDatabaseIfNeeded
{
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSString *folderPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES) objectAtIndex:0];
// First, test for existence.
if (![fileManager fileExistsAtPath:folderPath])
[fileManager createDirectoryAtPath:folderPath withIntermediateDirectories:YES attributes:nil error:&error]; //Create folder
NSString *dbPath = [folderPath stringByAppendingPathComponent:@"subjects.sqlite"];
BOOL success = [fileManager fileExistsAtPath:dbPath];
if(!success)
{
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"subjects.sqlite"];
success = [fileManager copyItemAtPath:defaultDBPath toPath:dbPath error:&error];
if (!success)
NSAssert1(0, @"subjects.sqlite : Failed to create writable database file with message '%@'.", [error localizedDescription]);
}
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
/** Database copy is not exist **/
[self copyDatabaseIfNeeded]; // Call this way
}