2010年8月21日 星期六

iPhone SQLite 新增一直失敗找到原因了




一開始的部份就不再說明教學了(是我太懶),讓大家參考這三個網站

1.iPhone Tutorial: Using SQLite3 database
http://ved-dimensions.blogspot.com/2009/03/iphone-development-sqlite3-populating.html

2.SQLite Tutorial - Saving images in the database
http://www.iphonesdkarticles.com/2009/02/sqlite-tutorial-saving-images-in.html

3.How do you insert an image into SQLite on the iPhone?
http://stackoverflow.com/questions/737443/how-do-you-insert-an-image-into-sqlite-on-the-iphone

今天為了要讓iPhone能透過讀取xml方式,取得更新的圖片url,得到url之後希望把圖片存到SQLite內,搞了超久一直失敗...
首先出現out of memory,光這個問題就找一個下午=.=,最後認真看到國外網友,它點出了db沒有正確讀到才會發生問題,下面這隻method就是連線成功的方式

- (void) getNewDBConnection{
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"data.sqlite"];
BOOL success = [fileManager fileExistsAtPath:path];
if (sqlite3_open([path UTF8String], &database) == SQLITE_OK) {
NSLog(@"Database Successfully Opened :)");
} else {
NSLog(@"Error in opening database :(");
}
}

接下來連線成功之後遇到第二個error : no such table: item ,這個問題也讓人很吐血,明明在resource下有一個data.sqlite,我也用Firefox plugin 的SQLite Manager 建好table與欄位,為什麼會告訴我找不到item這個table呢。最後我把上面的method中的path路徑 NSlog出來才看到原來根本不是在resource下的data.sqlite,原來它存取的是/Users/Maccc/Library/Application Support/iPhone Simulator/4.0/Applications/87386C6E-CCBC-48BF-A121-CF9900D4E0C3/Documents/data.sqlite

insert 至db的method

- (void) addData:(UIImage*)image {
NSString *title=[NSString stringWithString:@"test"];
NSData *ImageData = UIImagePNGRepresentation(image);
NSInteger Imagelen = [ImageData length];
if(addStmt == nil) {
const char *sql = "insert into item(title,imageData) values(?,?)";
if(sqlite3_prepare_v2(database, sql, -1, &addStmt, NULL) != SQLITE_OK)
NSLog(@"Error while creating add statement. '%s'", sqlite3_errmsg(database));
}

sqlite3_bind_text(addStmt, 1, [title UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_blob(addStmt, 2, [ImageData bytes], Imagelen, SQLITE_TRANSIENT);
if(SQLITE_DONE != sqlite3_step(addStmt))
NSLog(@"Error while inserting data. '%s'", sqlite3_errmsg(database));
else
sqlite3_last_insert_rowid(database);
//Reset the add statement.
sqlite3_reset(addStmt);
}

如果你有要轉換UImage為NSData可以用此method

- (UIImage*)loadImageFromUrl:(NSString*)url
{
NSURL *picUrl = [NSURL URLWithString:url];
NSData *picData = [NSData dataWithContentsOfURL:picUrl];
UIImage *image = [UIImage imageWithData:picData];
return image;
}

這樣你轉完後就可以存進db了..

沒有留言:

張貼留言