如何从NSData SQLite blob获取UIImage

时间:2013-11-19 10:10:51

标签: ios objective-c sqlite uiimage nsdata

我正在尝试获取网站的favicon,我保存在sqlite中。 获得NSData时,它不是零,但当我尝试转换为UIImage时 - UIImage为零。 有我的代码:

-(NSMutableArray *) historyList{
    sqlite3 *db;

    thehistory = [[NSMutableArray alloc] initWithCapacity:100];
    @try {
        NSFileManager *fileMgr = [NSFileManager defaultManager];

        NSString *dbPath = strMessage;

        BOOL success = [fileMgr fileExistsAtPath:dbPath];
        if(!success)
        {
        }
        if(!(sqlite3_open([dbPath UTF8String], &db) == SQLITE_OK))
        {
            NSLog(@"An error has occured: %s", sqlite3_errmsg(db));

        }


        const char *sql = "SELECT * FROM HITSORY";
        sqlite3_stmt *sqlStatement;
        if(sqlite3_prepare(db, sql, -1, &sqlStatement, NULL) != SQLITE_OK)
        {
             NSLog(@"Problem with prepare statement:  %s", sqlite3_errmsg(db));
        }else{

            while (sqlite3_step(sqlStatement)==SQLITE_ROW) {
                HistoryOBJ *author = [[HistoryOBJ alloc]init];//this is NSObject 
                author.title = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement,1)];
                author.url = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement,2)];
                NSData *imageData = [[NSData alloc] initWithBytes:sqlite3_column_blob(sqlStatement, 3) length: sqlite3_column_bytes(sqlStatement, 3)];
//imageData is saved favicon from website.


 if (imageData!=nil) {
                    NSLog(@"THERE imageData IS NOT NIL");//There data is not nil.

                }
                UIImage *image = [UIImage imageWithData:imageData];

我得到了我的错误,image总是为零。

if (image==nil) {
                        NSLog(@"THERE image IS NIL");//There is my problem

                    }
                author.icon = image;//author.icon is UIImage variable

                [thehistory addObject:author];
            }
        }
    }
    @catch (NSException *exception) {
        NSLog(@"Problem with prepare statement:  %s", sqlite3_errmsg(db));
    }
    @finally {
        sqlite3_close(db);

        return thehistory;
    }
}

我在那里缺少什么?

1 个答案:

答案 0 :(得分:0)

似乎NSData需要一些解码。 您可以使用GMTBase.64进行数据编码和解码。

注意:不要将blob写入sqlite。您可以将数据写入Documents目录并将相应的路径保存到Sqlite中。并且retreiving从sqlite获取路径并从文档目录中读取数据以获得相应的路径。