I'm trying to send many asynchronous request to php file that shows my data as json code and in the response I parse the json so I added the following in ViewDidload:
NSURLRequest *aboutRequest = [self getDataFromServer:#"http://al-awal.com/Rashad/iPhonePhp/about.php"];
aboutConn = [[NSURLConnection alloc] initWithRequest:aboutRequest delegate:self];
NSURLRequest *wisdomRequest = [self getDataFromServer:#"http://al-awal.com/Rashad/iPhonePhp/wisdomtoday.php"];
wisdomConn = [[NSURLConnection alloc] initWithRequest:wisdomRequest delegate:self];
then
-(NSURLRequest *) getDataFromServer:(NSString *)phpUrl{
responseData = [NSMutableData data];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:phpUrl]];
return request;
}
then I added:
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
sqlite3 *database;
if(sqlite3_open([[rashadDB databasePath] UTF8String], &database) == SQLITE_OK) {
if (connection == aboutConn) {
NSLog(#"get from table about");
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSString *json_string = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSArray *statuses = [parser objectWithString:json_string error:nil];
for (NSDictionary *status in statuses)
{
NSString *sAboutID = [status objectForKey:#"ID"];
NSString *sPhone1 = [status objectForKey:#"Phone1"];
NSString *sPhone2 = [status objectForKey:#"Phone2"];
NSString *sJawal = [status objectForKey:#"Jawal"];
NSString *sFax = [status objectForKey:#"Fax"];
NSString *sWebSite = [status objectForKey:#"WebSite"];
NSString *sEmail = [status objectForKey:#"Email"];
NSString *sAddress = [status objectForKey:#"Address"];
int sAboutID2 = [sAboutID intValue];
NSLog(#"in server, aboutID = %d, Phone1 = %#, Phone2 = %#, Jawal = %#, Fax = %#, WebSite = %#, Email = %#, Address = %#",sAboutID2, sPhone1, sPhone2, sJawal, sFax, sWebSite, sEmail, sAddress);
sqlite3_exec(database, [[NSString stringWithFormat:#"INSERT OR ABORT INTO About VALUES(%d, '%#', '%#', '%#', '%#', '%#', '%#', '%#')",sAboutID2, sPhone1, sPhone2, sJawal, sFax, sWebSite, sEmail, sAddress] UTF8String], NULL, NULL, NULL);
sqlite3_exec(database, [[NSString stringWithFormat:#"UPDATE About set Phone1 = '%#', Phone2 = '%#', Jawal = '%#', Fax = '%#', WebSite = '%#', Email = '%#', Address = '%#' Where aboutID = %d", sPhone1, sPhone2, sJawal, sFax, sWebSite, sEmail, sAddress, sAboutID2] UTF8String], NULL, NULL, NULL);
}
} else if (connection == wisdomConn) {
NSLog(#"get from table wisdoms");
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSString *json_string = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSArray *statuses = [parser objectWithString:json_string error:nil];
for (NSDictionary *status in statuses)
{
NSString *sWisdomTodayID = [status objectForKey:#"ID"];
NSString *sContent = [status objectForKey:#"Content"];
NSString *sAuthorName = [status objectForKey:#"AuthorName"];
NSString *sDateCreate = [status objectForKey:#"DateCreate"];
NSString *sEnable = [status objectForKey:#"Enable"];
int sWisdomTodayID2 = [sWisdomTodayID intValue];
int sEnable2 = [sEnable intValue];
NSLog(#"wisdomTodayID = %#, Content = '%#', AuthorName = '%#', DateCreate = '%#', Enable = %#", sWisdomTodayID, sContent, sAuthorName, sDateCreate, sEnable);
sqlite3_exec(database, [[NSString stringWithFormat:#"INSERT OR ABORT INTO WisdomToday VALUES(%d, '%#', '%#', '%#', %d)",sWisdomTodayID2, sContent, sAuthorName, sDateCreate, sEnable2] UTF8String], NULL, NULL, NULL);
sqlite3_exec(database, [[NSString stringWithFormat:#"UPDATE WisdomToday set Content = '%#', AuthorName = '%#', DateCreate = '%#', Enable = %d Where wisdomTodayID = %d", sContent, sAuthorName, sDateCreate, sEnable2, sWisdomTodayID2] UTF8String], NULL, NULL, NULL);
}
}
} // sqlite3 open end
sqlite3_close(database);
}
the first if condition --> if(connection == aboutConn) works ok with me and I got my output but the other if condition --> if (connection == wisdomConn) only gives me this output NSLog(#"get from table wisdoms"); and not go throw the for loop.
Is there are any wrong in my code?
You are not closing braces properly...
Before opening the brace for else - if condition you should close the brace for if_condition..
Some of your relevant code is missing (the NSConnectionDataDelegate methods). But it would seem that you are using one instance variable, responseData, to build up both return values. This would mean that some times you would get the faster response data only; and other times you would get mixed data in the same NSMutableData object.
Related
I have HTML webpage with lot of images and live contents. I need to parse the data from the webpage(HTML) and show in the iPhone app. Am using the following code to parse the HTML content. But i don't know how to parse the sub tags in the tags?
{
NSURL *url = [NSURL URLWithString:#"http://www.samplewebpage.com/vd/t/1/830.html"];
NSData *data = [[NSData alloc] initWithContentsOfURL:url];
NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"Response : %#", responseString);
NSMutableArray *imageURLArray = [[NSMutableArray alloc] init];
NSMutableArray *divClassArray = [[NSMutableArray alloc] init];
//NSString *regexStr = #"<A HREF=\"([^>]*)\">";
// For image : 1. img src=\"([^>]*)\" 2. <img src=\"([^>]*)\">
// For getting Class div class
NSString *regularExpressString = #"div class=\"([^>]*)\"";
NSError *error;
NSInteger i =0;
while (i<[responseString length])
{
NSRegularExpression *testRegularExpress = [NSRegularExpression regularExpressionWithPattern:regularExpressString options:NSRegularExpressionCaseInsensitive error:&error];
if( testRegularExpress == nil )
{
NSLog( #"Error making regex: %#", error );
}
NSTextCheckingResult *textCheckingResult = [testRegularExpress firstMatchInString:responseString options:0 range:NSMakeRange(i, [responseString length]-i)];
NSRange range = [textCheckingResult rangeAtIndex:1];
if (range.location == 0)
{
break;
}
NSString *classNameString = [responseString substringWithRange:range];
NSLog(#"Div Class Name : %#", classNameString);
[divClassArray addObject:classNameString];
i= range.location;
//NSLog(#"Range.location : %i",range.location);
i=i+range.length;
}
NSLog(#"divClass Array : %#, Count : %d", divClassArray, [divClassArray count]);
}
Response:
<div class="phoneModelItems" style="width:30%;margin-right:4px;">Nokia Model</div>
I want to get the text Nokia Model from the class phoneModelItems. Can you please tell me how to retrieve the text 'Nokia Model'? Thanks in advance.
Here is my Regular Expression for your problem:
<div\sclass=\"phoneModelItems\".*?><a\shref.*?>(.*?)<\/a><\/div>
you can test it on Rubular
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
}
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 a string in this format :- { panel : {start : [{"element_id" : 0, "element_name" :0, "element_image" : 0, "element_desc" : 0, "element_dob" : 0, "awards" :0},]} how can I parse this string. please help me to overcome this problem. I tried SBJSon - code: -
NSLog(#"response string before = %#", responseStr);
NSData *fileData = [NSData dataWithContentsOfFile:responseStr];
NSString *responseString = [[NSString alloc] initWithData:fileData encoding:NSUTF8StringEncoding];
NSLog(#"response string after = %#", responseString);
NSError *jsonError = nil;
NSDictionary *feed = nil;
SBJsonParser *json = [[SBJsonParser new] autorelease];
feed = [json objectWithString:responseString error:&jsonError];
NSLog(#"feed = %#", feed);
if ([jsonError code]==0) {
// get the array of "results" from the feed and cast to NSArray
NSMutableArray *localObjects = [[[NSMutableArray alloc] init] autorelease];
NSArray *results= (NSArray *)[feed valueForKey:#"start"];
// loop over all the results objects and print their names
int ndx;
for (ndx = 0; ndx < results.count; ndx++)
{
[localObjects addObject:(NSDictionary *)[results objectAtIndex:ndx]];
}
NSLog(#"local objects = %#", localObjects);
}
the NSDictionary feed is getting nil value in NSLog..
Try the following one...
SBJSON *json = [[SBJSON new] autorelease];
NSDictionary *dictResponse = (NSDictionary*) [json objectWithString:sitesResponse error:nil];
You can use Regular Expressions (wiki). Take sources from: RegexKit, add to linker flags "-fopenmp" and use in NSString message "stringByMatching".
For example, if you want take "element_name":
NSString* str = [your_string stringByMatching:#"element_name\".*:(.*?)," capture: 1L];
I'm trying to do an insert statement with SQLite and I'm sure I must be doing something stupid, but I can't figure out how to get it to work.
The error I'm getting is: "Error preparing statement"
Here's my code:
NSString *json_string = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
[responseData release];
// Create new SBJSON parser object
SBJsonParser *parser = [[SBJsonParser alloc] init];
// parse the JSON response into an object
NSDictionary *download = [parser objectWithString:json_string error:nil];
NSDictionary *buildings = [download objectForKey:#"buildings"];
// Open DB
sqlite3 *db = [RLSampleAppDelegate getNewDBConnection];
// Buildings
for (NSDictionary *building in buildings)
{
NSDictionary *thisbuilding = [building objectForKey:#"building"];
NSLog(#"%#", [thisbuilding objectForKey:#"buildingname"]);
sqlite3_stmt *statement = nil;
NSString* someString = [NSString stringWithFormat:#"INSERT INTO building (buildingid, buildingname) VALUES (\'%#\', \'%#\')", [thisbuilding objectForKey:#"buildingid"], [thisbuilding objectForKey:#"buildingname"]];
NSLog(#"somestring: %#", someString);
const char *sql = (const char *) someString;
if(sqlite3_prepare_v2(db, sql, -1, &statement, NULL)!=SQLITE_OK)
NSAssert1(0,#"Error preparing statement",sqlite3_errmsg(db));
while(sqlite3_step(statement) == SQLITE_DONE){}
sqlite3_finalize(statement);
}
[json_string release];
You can't use a NSString instance in the SQLite3 API. You need a pure C string.
So, try changing this:
const char *sql = (const char *) someString;
Into:
const char *sql = [someString cStringUsingEncoding:[NSString defaultCStringEncoding]];
Try this:
sqlite3_prepare_v2(db, [someString UTF8String], -1, &statement, nil)
First you need sure that you get database file from Document or Library folder of simulator. Because you can not insert databases stored in the app resources. And try my code.
NSString *json_string = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
[responseData release];
// Create new SBJSON parser object
SBJsonParser *parser = [[SBJsonParser alloc] init];
// parse the JSON response into an object
NSDictionary *download = [parser objectWithString:json_string error:nil];
NSDictionary *buildings = [download objectForKey:#"buildings"];
// Open DB
sqlite3 *db = [RLSampleAppDelegate getNewDBConnection];
// Buildings
for (NSDictionary *building in buildings)
{
NSDictionary *thisbuilding = [building objectForKey:#"building"];
NSLog(#"%#", [thisbuilding objectForKey:#"buildingname"]);
NSString* someString = [NSString stringWithFormat:#"INSERT INTO building (buildingid, buildingname) VALUES ('%#','%#')", [thisbuilding objectForKey:#"buildingid"], [thisbuilding objectForKey:#"buildingname"]];
const char *sql = [someString UTF8String];
char *error;
if (sqlite3_exec(db, sql, NULL, NULL, &error)==SQLITE_OK) {
NSLog(#"insert success.");
}
}
[json_string release];