How to parse HTML sub tags in iPhone app? - iphone

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

Related

How to retrieve all country name with counting to NSArray from NSDictionary?

Here is my dictionary result.
"continent_code" = EU;
"country_code" = gb;
"country_id" = 169;
"country_name" = "United Kingdom";
NSString *responseString = [[NSString alloc] initWithData:responseData
encoding:NSUTF8StringEncoding];
NSDictionary *LoginResult = (NSDictionary*)[responseString JSONValue];
I want to retrieve only country name to NSArray from dictionary.
Try This ::
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:webData options:NSJSONReadingMutableContainers error:&error];
NSLog(#" Value :: %#", [[jsonArray JSONRepresentation] JSONValue]);
for (NSDictionary *item in jsonArray) {
NSLog(#" Item :::::> %#", [item objectForKey:#"country_name"]);
}
Hope, It'll help you.
NSMutableArray *wholeJsonArray = [LoginResult objectForKey:#"RootName"];
NSMutableArray *loginArray = [[NSMutableArray alloc]init];
for(int i = 0 ; i<[loginArray count];i++)
{
NSString *countryName=[[loginArray objectAtIndex:i]objectForKey:#"country_name"];
[loginArray addObject:countryName];
}
Good luck !!
The Correct Method to fill countryArray :
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:yourResponseData options:kNilOptions error:&error];
NSArray* getMAS_CR = [(NSDictionary*)json objectForKey:#"yourKeyRootResult"];
NSMutableArray *countryArray = [[NSMutableArray alloc]init];
for (NSDictionary *rr in getMAS_CR)
{
NSString *cName = [NSString stringWithFormat:#"%#",[rr objectForKey:#"country_name"]];
[countryArray addObject:cName];
}
NSLog(#"countryArray :: %#",countryArray);
GoodLuck.

Parsing data from json to iphone application

I am parsing data from iphone app to json from server but it does not get data from the json
i am using following code
To get Data from json
here is the link of my json data
http://celeritas-solutions.com/emrapp/surveyDescription.php?user_id=ali40
NSString*user=#"ali40";
NSString *url=[NSString stringWithFormat:#"http://celeritas-solutions.com/emrapp/surveyDescription.php?user_id=%#",user];
NSLog(url);
NSArray *tempArray =[[DataManager staticVersion] startParsing:url];
for (int i = 0; i<[tempArray count]; i++) {
id *item = [tempArray objectAtIndex:i];
NSDictionary *dict = (NSDictionary *) item;
ObjectData *theObject =[[ObjectData alloc] init];
[theObject setUser_id:[dict objectForKey:#"user_id"]];
[theObject setSurvey_id:[dict objectForKey:#"survey_id"]];
[theObject setSurvey_title:[dict objectForKey:#"survey_Title"]];
[theObject setSurvey_Description:[dict objectForKey:#"survey_Description"]];
[theObject setDate_Created:[dict objectForKey:#"date_Created"]];
[surveyList addObject:theObject];
[theObject release];
theObject=nil;
int count =[surveyList count];
NSLog(#"Total is %d",count);
DataManager Class
DataManager *theInstance;
+ (id)staticVersion{
if(!theInstance){
theInstance = [[DataManager alloc] init];
}
return theInstance;
}
- (NSMutableArray *) startParsing:(NSString *)theURLString {
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#",theURLString]];
NSString *fileContent= [NSString stringWithContentsOfURL:url];
SBJSON *parser = [[SBJSON alloc] init];
NSDictionary *data = (NSDictionary *) [parser objectWithString:fileContent error:nil];
NSArray *items = (NSArray *) data ;
return items;
int count=[items count];
NSLog(#"This is testing %d",count);
}
You json is not correct.
It should be like this:
{"ali40":[{"user_id":"ali40","survey_id":"1","survey_title":"Resturant Survey","survey_description":"Survey To get feedback from clients about food quality and any suggestion to improve the service","date_created":"2012-07-24 22:39:14","color":"[UIColor GrayColor]"},{"user_id":"ali40","survey_id":"2","survey_title":"Travel Servey","survey_description":"Toursim Survey","date_created":"2012-07-25 00:43:42","color":"[UIColor greyColor]"}]}
This code returns not null result
NSString*user=#"ali40";
NSString *url=[NSString stringWithFormat:#"http://celeritas-solutions.com/emrapp/surveyDescription.php?user_id=%#",user];
NSLog(#"%#",url);
NSData* data = [NSData dataWithContentsOfURL:
[NSURL URLWithString: url]];
__autoreleasing NSError* error = nil;
id result = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
if (error != nil) NSLog(#"%#",error);
NSLog(#"%#",result);
Output:
2012-07-26 10:26:22.226 test[2511:f803] (
{
color = "[UIColor GrayColor]";
"date_created" = "2012-07-24 22:39:14";
"survey_description" = "Survey To get feedback from clients about food quality and any suggestion to improve the service";
"survey_id" = 1;
"survey_title" = "Resturant Survey";
"user_id" = ali40;
},
{
color = "[UIColor greyColor]";
"date_created" = "2012-07-25 00:43:42";
"survey_description" = "Toursim Survey";
"survey_id" = 2;
"survey_title" = "Travel Servey";
"user_id" = ali40;
}
)
If you json returns many records you need modify your json file
{"users":[{"user_id":"ali40","survey_id":"1","survey_title":"Resturant Survey","survey_description":"Survey To get feedback from clients about food quality and any suggestion to improve the service","date_created":"2012-07-24 22:39:14","color":"[UIColor GrayColor]"},{"user_id":"ali40","survey_id":"2","survey_title":"Travel Servey","survey_description":"Toursim Survey","date_created":"2012-07-25 00:43:42","color":"[UIColor greyColor]"}]}
Then you get the array of records:
NSArray *allItems = [result objectForKey:#"users"];
for (int i=0; i<allItems.count; ++i) {
NSDictionary *item = [allItems objectAtIndex:i]; //here you get every user
NSString *user_id=[item objectForKey:#"user_id"];
NSLog(#"user_id %#",user_id);
}

retrieve all data of nsarray

I'm using JSON parsing to get data from MySql by using php
I got all data I want, But when I want to print this data I created a for loop but It gives me the last element only .. this is my code
in DidViewLoad:
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *phpUrl = #"http://dt-works.com/eman/bookOwn.php";
NSString *dbName = #"dbName";
NSString *localHost = #"localhost";
NSString *dbUser = #"dbUser";
NSString *dbPwd = #"dbPwd";
int u_id = 1;
NSString *user_id = [NSString stringWithFormat:#"%d",u_id];
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:phpUrl]];
[request setHTTPMethod:#"POST"];
NSString *post = [[NSString alloc] initWithFormat:#"dbName=%#&localHost=%#&dbUser=%#&dbPwd=%#&user_id=%#&submit=", dbName, localHost, dbUser, dbPwd, user_id];
[request setHTTPBody:[post dataUsingEncoding:NSUTF8StringEncoding]];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSArray *statuses = [parser objectWithString:json_string error:nil];
int arraySize = [statuses count];
for (NSDictionary *status in statuses)
{
bo_id2 = [status objectForKey:#"bo_id"];
bo_name2 = [status objectForKey:#"bo_name"];
bo_au_id2 = [status objectForKey:#"bo_au_id"];
bo_pub_id2 = [status objectForKey:#"bo_pub_id"];
bo_num_pages2 = [status objectForKey:#"bo_num_pages"];
bo_publish_year2 = [status objectForKey:#"bo_publish_year"];
}
NSLog(#"size of array is: %d", arraySize);
for (int i=0; i<arraySize; i++) {
NSLog(#"%d:",i);
// here I want to retrieve all array elements .. when I try
NSLog(#"Book id: %# - book name: %#", bookId, bookName);
// this give me the last elemet only not all data
// I want to get the data here to use it later .. how ???
}
}
any help ??
You appear to just be reassigning the values of each object to an instance variable, an instance variable only points to one object, not all the ones you assign it to.
Most probably you must have been reintializing the array some where. Check that in the entire code.
NSLog(#"Book id: %# - book name: %#", bookId, bookName);
How do you get the bookId and bookName values in the NSLog above? Something missing in your code there.
You can try this :
for(NSDictionary *status in statuses) {
NSLog(#"Book id: %# - Book Name: %#", [status objectForKey:#"bo_id"], [status objectForKey: #"bo_name"]);
}
In other terms, if you want to use a second for loop, go the same way as the first one.
I don't quite understand why you have to use two for loop to finish the task, in your first loop
NSMutableArray *books = [[NSMutableArray alloc] init];
for(NSDictionary *status in statuses){
[books addObject:status];
}
Later when you want to retrieve any books, you can just call [books objectAtIndex:index].
Hopefully this can help.
You should be able to finish all the tasks you asked for.
Edit
If you just want just one element, bo_name for example you can use:
NSMutableArray *books =[[NSMutableArray alloc] init];
for(NSDictionary *status in statuses){
[books addObject:[status objectForKey:#"bo_name"]];
}

Arabic string in NSMutableArray or NSMutableDictionary

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.)

how to parse a string in iphone, objective c?

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];