I have my sqlite database. now i want syncing with icloud. I read blogs saying sqlite syncing with icloud is not supported. Either go for core data OR "Do what exactly core data does".
Now it is not posible for me to go for core data.So like second option "Do something similar to how CoreData syncs sqlite DBs: send "transaction logs" to iCloud instead and build each local sqlite file off of those."
please can anyone share any sample code for "transaction log" of sqlite OR can expalin in detail stepwise what i need to do?
1) I followed this link to create xml. You can download respective api from its github.Link is - http://arashpayan.com/blog/2009/01/14/apxml-nsxmldocument-substitute-for-iphoneipod-touch/
2) on button click:
-(IBAction) btniCloudPressed:(id)sender
{
// create the document with it’s root element
APDocument *doc = [[APDocument alloc] initWithRootElement:[APElement elementWithName:#"Properties"]];
APElement *rootElement = [doc rootElement]; // retrieves same element we created the line above
NSMutableArray *addrList = [[NSMutableArray alloc] init];
NSString *select_query;
const char *select_stmt;
sqlite3_stmt *compiled_stmt;
if (sqlite3_open([[app getDBPath] UTF8String], &dbconn) == SQLITE_OK)
{
select_query = [NSString stringWithFormat:#"SELECT * FROM Properties"];
select_stmt = [select_query UTF8String];
if(sqlite3_prepare_v2(dbconn, select_stmt, -1, &compiled_stmt, NULL) == SQLITE_OK)
{
while(sqlite3_step(compiled_stmt) == SQLITE_ROW)
{
NSString *addr = [NSString stringWithFormat:#"%#",[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiled_stmt,0)]];
addr = [NSString stringWithFormat:#"%##%#",addr,[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiled_stmt,1)]];
addr = [NSString stringWithFormat:#"%##%#",addr,[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiled_stmt,2)]];
addr = [NSString stringWithFormat:#"%##%#",addr,[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiled_stmt,3)]];
addr = [NSString stringWithFormat:#"%##%#",addr,[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiled_stmt,4)]];
addr = [NSString stringWithFormat:#"%##%#",addr,[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiled_stmt,5)]];
addr = [NSString stringWithFormat:#"%##%#",addr,[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiled_stmt,6)]];
addr = [NSString stringWithFormat:#"%##%#",addr,[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiled_stmt,7)]];
//NSLog(#"%#",addr);
[addrList addObject:addr];
}
sqlite3_finalize(compiled_stmt);
}
else
{
NSLog(#"Error while creating detail view statement. '%s'", sqlite3_errmsg(dbconn));
}
}
for(int i =0 ; i < [addrList count]; i++)
{
NSArray *addr = [[NSArray alloc] initWithArray:[[addrList objectAtIndex:i] componentsSeparatedByString:#"#"]];
APElement *property = [APElement elementWithName:#"Property"];
[property addAttributeNamed:#"id" withValue:[addr objectAtIndex:0]];
[property addAttributeNamed:#"street" withValue:[addr objectAtIndex:1]];
[property addAttributeNamed:#"city" withValue:[addr objectAtIndex:2]];
[property addAttributeNamed:#"state" withValue:[addr objectAtIndex:3]];
[property addAttributeNamed:#"zip" withValue:[addr objectAtIndex:4]];
[property addAttributeNamed:#"status" withValue:[addr objectAtIndex:5]];
[property addAttributeNamed:#"lastupdated" withValue:[addr objectAtIndex:6]];
[property addAttributeNamed:#"deleted" withValue:[addr objectAtIndex:7]];
[rootElement addChild:property];
[property release];
APElement *fullscore = [APElement elementWithName:#"FullScoreReport"];
[property addChild:fullscore];
[fullscore release];
select_query = [NSString stringWithFormat:#"SELECT AnsNo,Answer,AnswerScore,MaxScore,AnsIndex FROM FullScoreReport WHERE Addr_ID = %#",[addr objectAtIndex:0]];
select_stmt = [select_query UTF8String];
if(sqlite3_prepare_v2(dbconn, select_stmt, -1, &compiled_stmt, NULL) == SQLITE_OK)
{
while(sqlite3_step(compiled_stmt) == SQLITE_ROW)
{
APElement *answer = [APElement elementWithName:#"Answer"];
[answer addAttributeNamed:#"AnsNo" withValue:[NSString stringWithFormat:#"%#",[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiled_stmt,0)]]];
[answer addAttributeNamed:#"Answer" withValue:[NSString stringWithFormat:#"%#",[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiled_stmt,1)]]];
[answer addAttributeNamed:#"AnswerScore" withValue:[NSString stringWithFormat:#"%#",[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiled_stmt,2)]]];
[answer addAttributeNamed:#"MaxScore" withValue:[NSString stringWithFormat:#"%#",[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiled_stmt,3)]]];
[answer addAttributeNamed:#"AnsIndex" withValue:[NSString stringWithFormat:#"%#",[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiled_stmt,4)]]];
[fullscore addChild:answer];
[answer release];
}
sqlite3_finalize(compiled_stmt);
}
}
sqlite3_close(dbconn);
NSString *prettyXML = [doc prettyXML];
NSLog(#"\n\n%#",prettyXML);
//***** PARSE XML FILE *****
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [[paths objectAtIndex:0] stringByAppendingPathComponent:#"Properties.xml" ];
NSData *file = [NSData dataWithBytes:[prettyXML UTF8String] length:strlen([prettyXML UTF8String])];
[file writeToFile:path atomically:YES];
NSString *fileName = [NSString stringWithFormat:#"Properties.xml"];
NSURL *ubiq = [[NSFileManager defaultManager]URLForUbiquityContainerIdentifier:nil];
NSURL *ubiquitousPackage = [[ubiq URLByAppendingPathComponent:#"Documents"] URLByAppendingPathComponent:fileName];
MyDocument *mydoc = [[MyDocument alloc] initWithFileURL:ubiquitousPackage];
mydoc.xmlContent = prettyXML;
[mydoc saveToURL:[mydoc fileURL]forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL success)
{
if (success)
{
NSLog(#"XML: Synced with icloud");
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"iCloud Syncing" message:#"Successfully synced with iCloud." delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
}
else
NSLog(#"XML: Syncing FAILED with icloud");
}];
}
3)MyDocument.h file
#import <UIKit/UIKit.h>
#interface MyDocument : UIDocument
#property (strong) NSString *xmlContent;
#end
4)MyDocument.m file
#import "MyDocument.h"
#implementation MyDocument
#synthesize xmlContent,zipDataContent;
// Called whenever the application reads data from the file system
- (BOOL)loadFromContents:(id)contents ofType:(NSString *)typeName error:(NSError **)outError
{
// NSLog(#"* ---> typename: %#",typeName);
self.xmlContent = [[NSString alloc]
initWithBytes:[contents bytes]
length:[contents length]
encoding:NSUTF8StringEncoding];
[[NSNotificationCenter defaultCenter] postNotificationName:#"noteModified" object:self];
return YES;
}
// Called whenever the application (auto)saves the content of a note
- (id)contentsForType:(NSString *)typeName error:(NSError **)outError
{
return [NSData dataWithBytes:[self.xmlContent UTF8String] length:[self.xmlContent length]];
}
#end
5) now in ur appdelegate
- (void)loadData:(NSMetadataQuery *)queryData
{
for (NSMetadataItem *item in [queryData results])
{
NSString *filename = [item valueForAttribute:NSMetadataItemDisplayNameKey];
NSNumber *filesize = [item valueForAttribute:NSMetadataItemFSSizeKey];
NSDate *updated = [item valueForAttribute:NSMetadataItemFSContentChangeDateKey];
NSLog(#"%# (%# bytes, updated %#) ", filename, filesize, updated);
NSURL *url = [item valueForAttribute:NSMetadataItemURLKey];
MyDocument *doc = [[MyDocument alloc] initWithFileURL:url];
if([filename isEqualToString:#"Properties"])
{
[doc openWithCompletionHandler:^(BOOL success) {
if (success) {
NSLog(#"XML: Success to open from iCloud");
NSData *file = [NSData dataWithContentsOfURL:url];
//NSString *xmlFile = [[NSString alloc] initWithData:file encoding:NSASCIIStringEncoding];
//NSLog(#"%#",xmlFile);
NSXMLParser *parser = [[NSXMLParser alloc] initWithData:file];
[parser setDelegate:self];
[parser parse];
//We hold here until the parser finishes execution
[parser release];
}
else
{
NSLog(#"XML: failed to open from iCloud");
}
}];
}
}
}
6) now in parser method fetch data and insert/update as needed in database.
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)nameSpaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
if ([elementName isEqual:#"Property"])
{
NSLog(#"Property attributes : %#|%#|%#|%#|%#|%#|%#|%#", [attributeDict objectForKey:#"id"],[attributeDict objectForKey:#"street"], [attributeDict objectForKey:#"city"], [attributeDict objectForKey:#"state"],[attributeDict objectForKey:#"zip"],[attributeDict objectForKey:#"status"],[attributeDict objectForKey:#"lastupdated"],[attributeDict objectForKey:#"deleted"]);
}
//like this way fetch all data and insert in db
}
Related
I'm new to iPhone Development.
I have integrated iCloud storage in my application. I am successful in uploading documents on iCloud.
My document's size is around 126799 bytes. During uploading on iCloud I have made sure that a proper document is uploaded on iCloud by printing its length and content on the console. But when I am fetching document from iCloud it only gives me 3/4 of the content of that document. I have also checked this on console by printing its length and content.
/////====== variables are declared in interface file
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
NSURL *ubiq = [[NSFileManager defaultManager]
URLForUbiquityContainerIdentifier:nil];
if (ubiq)
{
NSLog(#"iCloud access at %#", ubiq);
// TODO: Load document...
[self loadDocument];
}
else
{
NSLog(#"No iCloud access");
}
}
- (void)loadDocument{
NSMetadataQuery *query = [[NSMetadataQuery alloc] init];
_query = query;
[query setSearchScopes:[NSArray arrayWithObject:NSMetadataQueryUbiquitousDocumentsScope]];
NSString *filename = #"supplimentlistdescription.txt";
NSPredicate *pred = [NSPredicate predicateWithFormat:#"%K like '%#'",filename,NSMetadataItemFSNameKey];
[query setPredicate:pred];
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:#selector(queryDidFinishGathering:)
name:NSMetadataQueryDidFinishGatheringNotification
object:query];
[query startQuery];
}
- (void)queryDidFinishGathering:(NSNotification *)notification {
NSMetadataQuery *query = [notification object];
[query disableUpdates];
[query stopQuery];
[[NSNotificationCenter defaultCenter] removeObserver:self
name:NSMetadataQueryDidFinishGatheringNotification
object:query];
_query = nil;
[self loadData:query];
}
- (void)loadData:(NSMetadataQuery *)query {
if ([query resultCount] == 1)
{
NSMetadataItem *item = [query resultAtIndex:0];
NSURL *url = [item valueForAttribute:NSMetadataItemURLKey];
Note *doc = [[Note alloc] initWithFileURL:url];
self.doc = doc;
[self.doc openWithCompletionHandler:^(BOOL success)
{
if (success)
{
NSLog(#"iCloud document opened");
}
else
{
NSLog(#"failed opening document from iCloud");
}
}
];
}
else
{
NSFileManager *filemgr = [NSFileManager defaultManager];
NSString *fileurlstring = [NSString stringWithFormat:#"Documents/Federal Rules of Civil Procedure"];
NSLog(#"fileurlstring:%#",fileurlstring);
ubiquityURL = [[filemgr URLForUbiquityContainerIdentifier:nil]
URLByAppendingPathComponent:fileurlstring];
[ubiquityURL retain];
NSLog(#"ubiquityURL1:%#",ubiquityURL);
if ([filemgr fileExistsAtPath:[ubiquityURL path]] == NO)
{
[ubiquityURL retain];
[filemgr createDirectoryAtURL:ubiquityURL withIntermediateDirectories:YES attributes:nil error:nil];
[ubiquityURL retain];
}
ubiquityURL = [ubiquityURL URLByAppendingPathComponent:#"supplimentlistdescription.txt"];
[ubiquityURL retain];
NSLog(#"ubiquityURL:%#",ubiquityURL);
Note *doc = [[Note alloc] initWithFileURL:ubiquityURL];
self.doc = doc;
[doc saveToURL:[doc fileURL]
forSaveOperation:UIDocumentSaveForCreating
completionHandler:^(BOOL success)
{
if (success) {
[doc openWithCompletionHandler:^(BOOL success)
{
NSLog(#"new document opened from iCloud");
}
];
}
}
];
}
}
-
///Note.h
#import <UIKit/UIKit.h>
#interface Note : UIDocument
#property (strong) NSString * noteContent;
#end
-
#import "Note.h"
#implementation Note
#synthesize noteContent;
- (BOOL)loadFromContents:(id)contents ofType:(NSString *)typeName
error:(NSError **)outError
{
if ([contents length] > 0)
{
self.noteContent = [[NSString alloc]
initWithBytes:[contents bytes]
length:[contents length]
encoding:NSUTF8StringEncoding];
NSLog(#"loadFromContents1");
NSLog(#"noteContent:%#",noteContent);
NSLog(#"noteContent.length:%d",noteContent.length);
}
else
{
// When the note is first created, assign some default content
self.noteContent = #"Empty";
}
return YES;
}
- (id)contentsForType:(NSString *)typeName error:(NSError **)outError
{
if ([self.noteContent length] == 0)
{
//self.noteContent = #"Empty";
NSString *FolderName = #"Federal Rules of Civil Procedure";
NSString *fileName = #"supplimentlistdescription.txt";
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
[FolderName retain];
NSString *fileName1 = [NSString stringWithFormat:#"%#/%#/%#",documentsDirectory,FolderName, fileName];
NSLog(#"fileName1:%#",fileName1);
NSData *data = [[NSData alloc]initWithContentsOfFile:fileName1];
noteContent =[[NSString alloc]initWithData:data encoding:NSMacOSRomanStringEncoding];
NSLog(#"noteContent:%#",noteContent);
NSLog(#"noteContent.length:%d",noteContent.length);
}
return [NSData dataWithBytes:[self.noteContent UTF8String]
length:[self.noteContent length]];
}
#end
Can you please tell me whats can be the problem? Any suggestion will be appreciated. Thanks
I got a same problem like your before.
You should use
for writing
[self.noteContent dataUsingEncoding:NSUTF8StringEncoding];
for reading
self.noteContent = [[NSString alloc] initWithData:contents encoding:NSUTF8StringEncoding];
Example :
- (BOOL)loadFromContents:(id)contents ofType:(NSString *)typeName error:(NSError **)outError
{
if ([contents length] > 0) {
self.noteContent = [[NSString alloc] initWithData:contents encoding:NSUTF8StringEncoding];
} else {
self.noteContent = #""; // When the note is created we assign some default content
}
[[NSNotificationCenter defaultCenter] postNotificationName:#"noteModified"
object:self];
return YES;
}
// Called whenever the application (auto)saves the content of a note
- (id)contentsForType:(NSString *)typeName error:(NSError **)outError
{
if ([self.noteContent length] == 0) {
self.noteContent = #"";
}
return [self.noteContent dataUsingEncoding:NSUTF8StringEncoding];
}
I have a problem when I add an arabic string to NSMutableArray or NSMutableDictionary.
Example:
NSMutableDictionary *data = [[NSMutableDictionary alloc]init];
[data setObject:#"فرسان" forKey:#"name"];
NSLog(#"%#",data);
Output:
2012-01-18 21:55:05.646 aa[367:207] {
name = "\U0641\U0631\U0633\U0627\U0646";
}
my problem exactly i save this data to sqlite [data objectForKey:#"name"] its saved \U0641\U0631\U0633\U0627\U0646 and when fetch data to to put it in UILabel or anything like it the text be \U0641\U0631\U0633\U0627\U0646
Any Help? Thank you :)
- (void)SaveMessage {
NSMutableDictionary *TableProperties = [[NSMutableDictionary alloc]init];
[TableProperties setObject:#"INSERT" forKey:#"Operation"];
[TableProperties setObject:#"savedmessages" forKey:#"tableName"];
NSString *string = [[NSString alloc]initWithFormat:#" %#",MessageBox.text];
[TableProperties setValue:string forKey:#"message"];
NSString *msgResult;
NSArray *result = [[DatabaseFunctions database] DataBaseOperation:TableProperties];
if ([[result objectAtIndex:0] isEqualToString:#"Done"])
msgResult = #"تم حفظ الرسالة بنجاح";
else
msgResult = #"لم تت العملية بنجاح حاول لاحقا";
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:#"حفظ الرسالة"
message:msgResult
delegate:self
cancelButtonTitle:#"موافق"
otherButtonTitles:nil, nil ];
[alert show];
}
- (NSArray *)DataBaseOperation:(NSMutableDictionary *)TableProperties{
NSMutableArray *retval = [[NSMutableArray alloc] init];
NSString *Operation = [TableProperties objectForKey:#"Operation"];
if ([Operation isEqualToString:#"SELECT" ]) {
NSString *tableColumns = [TableProperties objectForKey:#"tableColumns"];
NSString *tableName = [TableProperties objectForKey:#"tableName"];
NSString *tableWhere = [TableProperties objectForKey:#"tableWhere"];
NSString *tableOrder = [TableProperties objectForKey:#"tableOrder"];
NSString *tableLimit = [TableProperties objectForKey:#"tableLimit"];
NSString *Query;
if ([tableLimit isEqualToString:#"NO"]) {
Query = [[NSString alloc] initWithFormat:#"SELECT %# FROM %# WHERE %# ORDER BY %#",
tableColumns,tableName,tableWhere,tableOrder,tableLimit];
}else{
Query = [[NSString alloc] initWithFormat:#"SELECT %# FROM %# WHERE %# ORDER BY %# LIMIT %#",
tableColumns,tableName,tableWhere,tableOrder,tableLimit];
}
NSArray *FieldArray = [[TableProperties objectForKey:#"tableColumns"] componentsSeparatedByString:#","];
sqlite3_stmt *statement;
if (sqlite3_prepare_v2(_database, [Query UTF8String], -1, &statement, nil) == SQLITE_OK) {
while (sqlite3_step(statement) == SQLITE_ROW) {
NSMutableDictionary *Row = [[NSMutableDictionary alloc]init];
NSString *uniqueId = [[NSString alloc] initWithFormat:#"%i",sqlite3_column_int(statement, 0)];
[Row setObject:uniqueId forKey:#"uniqueId"];
for (int i = 1; i<[FieldArray count]; i++) {
NSString *column = [[NSString alloc] initWithUTF8String:(char *) sqlite3_column_text(statement, i)];
[Row setObject:column forKey:[FieldArray objectAtIndex:i]];
}
Objects *rowOfTable = [[Objects alloc] initSelectDataFromTables:Row];
Row = nil;
[retval addObject:rowOfTable];
}
sqlite3_finalize(statement);
}
}
else if([Operation isEqualToString:#"INSERT" ]) {
NSString *tableName = [TableProperties objectForKey:#"tableName"];
[TableProperties removeObjectForKey:#"Operation"];
[TableProperties removeObjectForKey:#"tableName"];
NSArray *Columns = [TableProperties allKeys];
NSArray *Values = [TableProperties allValues];
NSString *Query = [[NSString alloc] initWithFormat:#"INSERT INTO %# %# VALUES %#",tableName,Columns,Values];
sqlite3_stmt *statement;
if (sqlite3_prepare_v2(_database, [Query UTF8String], -1, &statement, nil) == SQLITE_OK)
if (SQLITE_DONE!=sqlite3_step(statement)){
NSLog(#"Error when inserting %s",sqlite3_errmsg(_database));
[retval addObject:#"Error"];
}else{
NSLog(#"Data inserted Successfully");
[retval addObject:#"Done"];
}
else{
NSLog(#"Error when inserting %s",sqlite3_errmsg(_database));
[retval addObject:#"Error"];
}
sqlite3_finalize(statement);
}
return retval;
}
When you log an object using %#, NSLog sends the description message to the object and prints the resulting string.
An NSDictionary responds to the description message by encoding its keys and values in a "safe" format, escaping non-ASCII characters using \U#### codes.
If you pass the Arabic string to NSLog directly, it will just print the string without the escape codes:
NSMutableDictionary *data = [[NSMutableDictionary alloc]init];
[data setObject:#"فرسان" forKey:#"name"];
NSLog(#"data = %#",data);
NSLog(#"string = %#", [data objectForKey:#"name"]);
Output:
2012-01-18 14:17:42.498 Animal[62723:f803] {
name = "\U0641\U0631\U0633\U0627\U0646";
}
2012-01-18 14:17:42.500 Animal[62723:f803] فرسان
If you don't like the way NSDictionary responds to description, you will have to write your own method to format a dictionary as a string and use it to log your dictionary.
Update
I have looked at the source code you posted that talks to sqlite. The problem is that you are turning the values array ([TableProperties allValues]) into a string using the %# format specifier. This sends the description method to the NSArray, which returns a string. Just like NSDictionary, NSArray formats the description string in a "safe" format, escaping non-ASCII characters using \U#### codes.
You need to write your own method that takes an array and turns it into a string and does not escape special characters. (It needs to escape quotes though.)
I have an application in which I am posting data to my server API database through HTTP POST method and get response in JSON format. I want to read the JSON data and save it in SQLite database. I have done with posting data to Web server API through HTTP POST method but reading the JSON data and saving it in database has not been achieved.
I have created a class which consists of all the JSON array objects.
This is .h file:
#import <Foundation/Foundation.h>
//TokenID":"Vao13gifem","isError":false,"ErrorMessage":"","Result":[{"UserId":"153","FirstName":"Rocky","LastName":"Yadav","Email":"rocky#itg.com","ProfileImage":null,"ThumbnailImage":null,"DeviceInfoId":"12"}],"ErrorCode":900}
//Terminating in response to SpringBoard's termination.
#interface Result : NSObject {
NSString * UserID;
NSString *FirstName;
NSString *LastName;
NSString *Email;
NSString *ProfileImage;
NSString *ThumbnailImage;
NSString *DeviceInfoId;
}
#property (nonatomic,retain) NSString *UserID;
#property (nonatomic,retain) NSString *FirstName;
#property (nonatomic,retain) NSString *LastName;
#property (nonatomic,retain) NSString *Email;
#property (nonatomic,retain) NSString *ProfileImage;
#property (nonatomic,retain) NSString *ThumbnailImage;
#property (nonatomic,retain) NSString *DeviceInfoId;
#end
This is .m file
#import "Result.h"
#implementation Result
#synthesize UserID;
#synthesize FirstName;
#synthesize LastName;
#synthesize Email;
#synthesize ProfileImage;
#synthesize ThumbnailImage;
#synthesize DeviceInfoId;
- (void)dealloc {
[super dealloc];
[UserID release];
[FirstName release];
[LastName release];
[Email release];
[ProfileImage release];
[ThumbnailImage release];
[DeviceInfoId release];
}
#end
This is my apicontroller.m
#import "apicontroller.h"
#import "Result.h"
#import <sqlite3.h>
#define DATABASE_NAME #"journey.sqlite"
#define DATABASE_TITLE #"journey"
#implementation apicontroller
#synthesize txtUserName;
#synthesize txtPassword;
#synthesize txtfirstName;
#synthesize txtlast;
#synthesize txtEmail;
#synthesize webData;
- (NSString *) getWritableDBPath {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
return [documentsDir stringByAppendingPathComponent:DATABASE_NAME];
}
-(void)createEditableCopyOfDatabaseIfNeeded
{
// Testing for existence
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:DATABASE_NAME];
NSLog(#"%#",writableDBPath);
success = [fileManager fileExistsAtPath:writableDBPath];
if (success)
return;
// The writable database does not exist, so copy the default to
// the appropriate location.
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath]
stringByAppendingPathComponent:DATABASE_NAME];
success = [fileManager copyItemAtPath:defaultDBPath
toPath:writableDBPath
error:&error];
if(!success)
{
NSAssert1(0,#"Failed to create writable database file with Message : '%#'.",
[error localizedDescription]);
}
}
-(void)sendRequest
{
UIDevice *device = [UIDevice currentDevice];
NSString *udid = [device uniqueIdentifier];
NSString *sysname = [device systemName];
NSString *sysver = [device systemVersion];
NSString *model = [device model];
NSLog(#"idis:%#",[device uniqueIdentifier]);
NSLog(#"system nameis :%#",[device systemName]);
NSLog(#"System version is:%#",[device systemVersion]);
NSLog(#"System model is:%#",[device model]);
NSLog(#"device orientation is:%d",[device orientation]);
NSString *post = [NSString stringWithFormat:#"Loginkey=%#&Password=%#&DeviceCode=%#&Firmware=%#&IMEI=%#",txtUserName.text,txtPassword.text,model,sysver,udid];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSLog(#"%#",postLength);
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:#"http://192.168.0.68:91/JourneyMapperAPI?RequestType=Login"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (theConnection) {
webData = [[NSMutableData data] retain];
NSLog(#"%#",webData);
}
else
{
}
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[webData setLength: 0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[webData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
[connection release];
[webData release];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *loginStatus = [[NSString alloc] initWithBytes: [webData mutableBytes] length:[webData length] encoding:NSUTF8StringEncoding];
NSLog(#"%#",loginStatus);
NSString *json_string = [[NSString alloc] initWithData:webData encoding:NSUTF8StringEncoding];
NSDictionary *result = [json_string JSONValue];
NSArray *values = [result objectForKey:#"Result"];
NSMutableArray *results = [[NSMutableArray alloc] init];
for (int index = 0; index<[values count]; index++) {
NSMutableDictionary * value = [values objectAtIndex:index];
Result * result = [[Result alloc] init];
result.UserID = [value objectForKey:#"UserId"];
result.FirstName = [value objectForKey:#"FirstName"];
result.LastName =[value objectForKey:#"LastName"];
result.Email =[value objectForKey:#"Email"];
result.ProfileImage =[value objectForKey:#"ProfileImage"];
result.ThumbnailImage =[value objectForKey:#"ThumbnailImage"];
result.DeviceInfoId =[value objectForKey:#"DeviceInfoId"];
[results addObject:result];
[result release];
}
for (int index = 0; index<[results count]; index++) {
Result * result = [results objectAtIndex:index];
//save the object variables to database here
[self createEditableCopyOfDatabaseIfNeeded];
NSString *filePath = [self getWritableDBPath];
sqlite3 *database;
if(sqlite3_open([filePath UTF8String], &database) == SQLITE_OK) {
const char *sqlStatement = "insert into UserInformation(UserID,DeviceId,FirstName,Email,) VALUES (?,?,?,?)";
sqlite3_stmt *compiledStatement;
if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {
sqlite3_bind_text( compiledStatement, 1, [result.UserID UTF8String],-1,SQLITE_TRANSIENT);
sqlite3_bind_text(compiledStatement, 2, [result.DeviceInfoId UTF8String],-1,SQLITE_TRANSIENT);
sqlite3_bind_text (compiledStatement, 3, [result.FirstName UTF8String],-1,SQLITE_TRANSIENT);
sqlite3_bind_text (compiledStatement, 4, [result.Email UTF8String],-1,SQLITE_TRANSIENT);
}
if(sqlite3_step(compiledStatement) != SQLITE_DONE ) {
NSLog( #"Save Error: %s", sqlite3_errmsg(database) );
}
else {
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"UIAlertView" message:#"Record added" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
alert = nil;
}
sqlite3_finalize(compiledStatement);
}
sqlite3_close(database);
}
[loginStatus release];
[connection release];
[webData release];
}
-(IBAction)click:(id)sender
{
[self sendRequest];
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
[txtfirstName resignFirstResponder];
[txtlast resignFirstResponder];
[txtUserName resignFirstResponder];
[txtPassword resignFirstResponder];
[txtEmail resignFirstResponder];
}
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
[super viewDidLoad];
//[self sendRequest];
}
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations.
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc. that aren't in use.
}
- (void)viewDidUnload {
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc {
[super dealloc];
}
#end
In the connectionFinishLoading method it does not compare each object, it directly prints the error in NSLog:
(Save Error:near")":syntax error);
How can I fix this error?
My guess is that the trailing comma in the list of columns in your SQL statement is causing the error:
const char *sqlStatement = "insert into UserInformation(UserID,DeviceId,FirstName,Email,) VALUES (?,?,?,?)";
Note that there’s a comma between Email and ).
Try:
const char *sqlStatement = "insert into UserInformation(UserID,DeviceId,FirstName,Email) VALUES (?,?,?,?)";
instead.
I have the following problem while i scroll the table view:
NSCFString objectAtIndex:]: unrecognized selector sent to instance
I create NSDictionary tableContents and when i scroll it becomes deallocated.
This is my code:
- (void)viewDidLoad {
lessonsInGroup1 = [NSMutableArray array];
lessonsInGroup2 = [NSMutableArray array];
lessonsInGroup1 = [self grabRowsInGroup:#"1"];
lessonsInGroup2 = [self grabRowsInGroup:#"2"];
NSDictionary *temp =[[NSDictionary alloc]initWithObjectsAndKeys:lessonsInGroup1,#"General Information",lessonsInGroup2,#"LaTeX Examples", nil];
//[[tableContents alloc] init];
self.tableContents =temp;
[temp release];
NSLog(#"table %#",self.tableContents);
NSLog(#"table with Keys %#",[self.tableContents allKeys]);
self.sortedKeys =[[self.tableContents allKeys] sortedArrayUsingSelector:#selector(compare:)];
NSLog(#"sorted %#",self.sortedKeys);
[lessonsInGroup1 release];
[lessonsInGroup2 release];
//[table reloadData];
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem;
[super viewDidLoad];
}
- (NSMutableArray *) grabRowsInGroup:(NSString*)GroupID{
NSMutableArray *groupOfLessons;
groupOfLessons = [[NSMutableArray alloc] init];
char *sqlStatement;
int returnCode;
sqlite3_stmt *statement;
NSString *databaseName;
NSString *databasePath;
// Setup some globals
databaseName = #"TexDatabase.sql";
// Get the path to the documents directory and append the databaseName
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [documentPaths objectAtIndex:0];
databasePath = [documentsDir stringByAppendingPathComponent:databaseName];
// Setup the database object
sqlite3 *database;
// Open the database from the users filessytem
if(sqlite3_open([databasePath UTF8String], &database) != SQLITE_OK) {
fprintf(stderr, "Error in opening the database. Error: %s",
sqlite3_errmsg(database));
sqlite3_close(database);
return;
}
sqlStatement = sqlite3_mprintf(
"SELECT * FROM Lessons WHERE LessonGroup = '%s';", [GroupID UTF8String]);
returnCode =
sqlite3_prepare_v2(database,
sqlStatement, strlen(sqlStatement),
&statement, NULL);
if(returnCode != SQLITE_OK) {
fprintf(stderr, "Error in preparation of query. Error: %s",
sqlite3_errmsg(database));
sqlite3_close(database);
return;
}
returnCode = sqlite3_step(statement);
while(returnCode == SQLITE_ROW) {
NSString *aLessonID = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 0)];
NSString *aLessonGroup = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 1)];
NSString *aLessonTopic = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 2)];
NSString *aLessonText = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 3)];
NSString *aLessonCode = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 4)];
NSString *aLessonPicture = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 5)];
/*NSLog(aLessonID);
NSLog(aLessonGroup);
NSLog(aLessonTopic);
NSLog(aLessonText);
NSLog(aLessonCode);
NSLog(aLessonPicture);*/
// Create a new busCit object with the data from the database
Lesson *lesson = [[Lesson alloc] initWithLessonID:aLessonID LessonGroup:aLessonGroup LessonTopic:aLessonTopic LessonText:aLessonText LessonCode:aLessonCode LessonPicture:aLessonPicture];
[groupOfLessons addObject:lesson];
returnCode = sqlite3_step(statement);
}
sqlite3_finalize(statement);
sqlite3_free(sqlStatement);
return [groupOfLessons autorelease];
}
What does your #property for tableofContents look like?
Also, you are going to run into issues with
[lessonsInGroup1 release];
[lessonsInGroup2 release];
because you are autoreleasing those in the grabRowsInGroup:
So, you don't need to call release them.
Looks like you are calling objectAtIndex on NSString. It should rather be some array
I am creating an application where I am using SQLite database to save data. But when I run my application I get the following errors:
#interface TDatabase : NSObject {
sqlite3 *database;
}
+(TDatabase *) shareDataBase;
-(BOOL) createDataBase:(NSString *)DataBaseName;
-(NSString*) GetDatabasePath:(NSString *)database;
-(NSMutableArray *) getAllDataForQuery:(NSString *)sql forDatabase:(NSString *)database;
-(void*) inseryQuery:(NSString *) insertSql forDatabase:(NSString *)database1;
#end
#import "TDatabase.h"
#import <sqlite3.h>
#implementation TDatabase
static TDatabase *SampleDataBase =nil;
+(TDatabase*) shareDataBase{
if(!SampleDataBase){
SampleDataBase = [[TDatabase alloc] init];
}
return SampleDataBase;
}
-(NSString *)GetDatabasePath:(NSString *)database1{
[self createDataBase:database1];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
return [documentsDirectory stringByAppendingPathComponent:database1];
}
-(BOOL) createDataBase:(NSString *)DataBaseName{
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:DataBaseName];
success = [fileManager fileExistsAtPath:writableDBPath];
if (success) return success;
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:DataBaseName];
success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
if (!success) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error!!!" message:#"Failed to create writable database" delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles:nil];
[alert show];
[alert release];
}
return success;
}
-(NSMutableArray *) getAllDataForQuery:(NSString *)sql forDatabase:(NSString *)database1{
sqlite3_stmt *statement = nil ;
NSString *path = [self GetDatabasePath:database1];
NSMutableArray *alldata;
alldata = [[NSMutableArray alloc] init];
if(sqlite3_open([path UTF8String],&database) == SQLITE_OK )
{
NSString *query = sql;
if((sqlite3_prepare_v2(database,[query UTF8String],-1, &statement, NULL)) == SQLITE_OK)
{
while(sqlite3_step(statement) == SQLITE_ROW)
{
NSMutableDictionary *currentRow = [[NSMutableDictionary alloc] init];
int count = sqlite3_column_count(statement);
for (int i=0; i < count; i++) {
char *name = (char*) sqlite3_column_name(statement, i);
char *data = (char*) sqlite3_column_text(statement, i);
NSString *columnData;
NSString *columnName = [NSString stringWithCString:name encoding:NSUTF8StringEncoding];
if(data != nil)
columnData = [NSString stringWithCString:data encoding:NSUTF8StringEncoding];
else {
columnData = #"";
}
[currentRow setObject:columnData forKey:columnName];
}
[alldata addObject:currentRow];
}
}
sqlite3_finalize(statement);
}
sqlite3_close(database);
return alldata;
}
-(void*) inseryQuery:(NSString *) insertSql forDatabase:(NSString *)database1{
sqlite3_stmt *statement = nil ;
NSString *path = [self GetDatabasePath:database1];
if(sqlite3_open([path UTF8String],&database) == SQLITE_OK )
{
if((sqlite3_prepare_v2(database,[insertSql UTF8String],-1, &statement, NULL)) == SQLITE_OK)
{
if(sqlite3_step(statement) == SQLITE_OK){
}
}
sqlite3_finalize(statement);
}
sqlite3_close(database);
return insertSql;
}
NSString *sql = #"select * from Location";
const location = [[TDatabase shareDataBase] getAllDataForQuery:sql forDatabase:#"journeydatabase.sqlite"];//1
NSString* insertSql = [NSString stringWithFormat:#"insert into Location values ('city','name','phone')"];//2
const insert =[[TDatabase shareDataBase] inseryQuery:insertSql forDatabase:#"journeydatabase.sqlite"];//3
in line no 1,2,3 I get the same error:
initializer element is not constant
What might be the problem?
#rani writing your own methods to deal with sqlite database is very painstaking. You should use fmdb wrapper class or use core data. I personally prefer fmdb. Initially I was doing the same way you were. I found about fmdb here. After using it I had to write very little code whenever I have to deal With sqlite db.