Many NSXMLParsers in a singleview xcode - xcode4

I have to parse two XML files in a singleview and so I m using two NSXMLParsers to get it.But he proble m is one parser is getting recognized and second parser is not getting recognized...I mean after the debugger passes this line [parser1 parse] it should go to the delegates didStartElement,foundcharacters and didEndElement but in my case the debugger is not entering those delegates.It is simply jumping to [parser1 release] stmnt.So those delegates are not getting recognized for parser1.Y is it so ?
I have written this :
NSXMLParser *parser = [[NSXMLParser alloc] initWithContentsOfURL:Url];
[parser setDelegate:self];
[parser setShouldProcessNamespaces:NO];
[parser setShouldReportNamespacePrefixes:NO];
[parser setShouldResolveExternalEntities:NO];
[parser parse];
[parser release];
NSXMLParser *parser1 = [[NSXMLParser alloc] initWithContentsOfURL:Url1];
[parser1 setDelegate:self];
[parser1 setShouldProcessNamespaces:NO];
[parser1 setShouldReportNamespacePrefixes:NO];
[parser1 setShouldResolveExternalEntities:NO];
[parser1 parse];
[parser1 release];
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
if([elementName isEqualToString:#"TimeList"])
{
arr1=[[NSMutableArray alloc] init];
drr1=[[NSMutableDictionary alloc] init];
}
if([elementName isEqualToString:#"Company"])
{
drr1=[[NSMutableDictionary alloc] init];
}
srr1=[[NSMutableString alloc] init];
}
-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
[srr1 appendString:string];
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
if([elementName isEqualToString:#"ID"])
{
[drr1 setObject:srr1 forKey:#"ID"];
[srr1 release],srr1=nil;
return;
}
if([elementName isEqualToString:#"Company"])
{
[arr1 addObject:drr1];
}
if([elementName isEqualToString:#"TimeList"])
{
[drr1 release];
}
[srr1 release],srr1=nil;
}
- (void)parser1:(NSXMLParser *)parser1 didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
if([elementName isEqualToString:#"categorylist"])
{
arr2=[[NSMutableArray alloc] init];
drr2=[[NSMutableDictionary alloc] init];
}
if([elementName isEqualToString:#"lookup"])
{
drr2=[[NSMutableDictionary alloc] init];
}
srr2=[[NSMutableString alloc] init];
}
-(void)parser1:(NSXMLParser *)parser1 foundCharacters:(NSString *)string{
[srr2 appendString:string];
}
- (void)parser1:(NSXMLParser *)parser1 didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
if([elementName isEqualToString:#"Code"])
{
[drr2 setObject:srr2 forKey:#"Code"];
[srr2 release],srr2=nil;
return;
}
if([elementName isEqualToString:#"lookup"])
{
[arr2 addObject:drr2];
}
if([elementName isEqualToString:#"categorylist"])
{
[drr2 release];
}
[srr2 release],srr2=nil;
}
The first parser is getting recognized and getting the data.But for the second parser didStartElement is not getting recognized...What could be the possible reason ?

I solved it by myself.Actually I declared a string and passed some value to it.While parsing it checks ,if that condition gets true then it parses ..
This is what I did:
NSXMLParser *parser = [[NSXMLParser alloc] initWithContentsOfURL:Url];
[parser setDelegate:self];
[parser setShouldProcessNamespaces:NO];
[parser setShouldReportNamespacePrefixes:NO];
[parser setShouldResolveExternalEntities:NO];
currentparser=#"1";
[parser parse];
[parser release];
NSXMLParser *parser = [[NSXMLParser alloc] initWithContentsOfURL:Url1];
[parser setDelegate:self];
[parser setShouldProcessNamespaces:NO];
[parser setShouldReportNamespacePrefixes:NO];
[parser setShouldResolveExternalEntities:NO];
currentparser=#"2";
[parser parse];
[parser release];
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
if(currentparser==#"1")
{
//do something
}
if(currentparser=#"2")
{
//do something
}
}
-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
if(currentparser==#"1")
{
//do something
}
if(currentparser=#"2")
{
//do something
}
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
if(currentparser==#"1")
{
//do something
}
if(currentparser=#"2")
{
//do something
}
}

Related

How to create sqlite custom file in ios?

I am working on application where using local database as sqlite.
Where I want to create custom file for sqlite I don't know how to do this.
Any help would be appreciated.
First of all add below file into your project.
https://github.com/ConnorD/simple-sqlite
Then create database.sqlite file into your project. Database contain user first nam,last name and profile picutre.
And add below code into your AppDelegate file.
- (void)createEditableCopyOfDatabaseIfNeeded
{
// First, test for existence.
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
// UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"testing" message:#"path for database" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
// [alert show];
// [alert release];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:#"Category_DB.sqlite"];
//NSLog(#"Default writableDBPath: %#",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:#"Category_DB.sqlite"];
//NSLog(#"Default : %#",defaultDBPath);
success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
// NSLog(#"Success");
if (!success) {
NSAssert1(0, #"Failed to create writable database file with message '%#'.", [error localizedDescription]);
}
}
Call this method into your didFinishLaunchingWithOptions
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[self createEditableCopyOfDatabaseIfNeeded];
return NO;
}
Now write below code into your view controller where you want to use queries.
-(void)databaseOpen
{
NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [path objectAtIndex:0];
NSString *myDBnew = [documentsDirectory stringByAppendingPathComponent:#"Category_DB.sqlite"];
myDatabase = [[Sqlite alloc] init];
[myDatabase open:myDBnew];
// NSLog(#"database opened");
}
For select query:
[self databaseOpen];
NSString *query_fetch=[NSString stringWithFormat:#"select Max(session_id) from Report"];
NSMutableArray *userData=[[myDatabase executeQuery:query_fetch]mutableCopy];
IF you want to save image to database
-(NSString *) getImagePath{
/* *** Modify on 16 01 2012 by Prerak *** */
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSError *error;
[[NSFileManager defaultManager] createDirectoryAtPath:documentsDirectory withIntermediateDirectories:YES attributes:nil error:&error];
return documentsDirectory;
}
IF you want to get image to database
arrProfilepic = [[NSMutableArray alloc]init];
NSError *error = nil;
NSString *stringPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
NSArray *filePathsArray = [[NSFileManager defaultManager] subpathsOfDirectoryAtPath: stringPath error:&error];
NSLog(#"File Path Array is %#",filePathsArray);
for(int i=0;i<[filePathsArray count];i++)
{
NSString *strFilePath = [filePathsArray objectAtIndex:i];
if ([[strFilePath pathExtension] isEqualToString:#"jpg"] || [[strFilePath pathExtension] isEqualToString:#"png"] || [[strFilePath pathExtension] isEqualToString:#"PNG"])
{
NSString *imagePath = [[stringPath stringByAppendingString:#"/"] stringByAppendingString:strFilePath];
NSData *data = [NSData dataWithContentsOfFile:imagePath];
//NSLog(#"Data %#", data);
if(data)
{
UIImage *image = [UIImage imageWithData:data];
NSLog(#"Image %#", image);
[arrProfilepic addObject:image];
}
}
}
NSLog(#"profile is %#",arrProfilepic);
For Insert query:
NSString *documentsDirectory = [self getImagePath];//save image to database
NSString *imagePath;
imagePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"User_%d.png",newid]];
NSString *relativePathImage1=nil;
NSArray *relativeArray=[imagePath componentsSeparatedByString:#"/Documents"];
UIImage *thumbImage;
thumbImage = [VcAddUser.portraitImageView.image imageScaledToFitSize:CGSizeMake(90, 90)];
NSData *thumbData = UIImageJPEGRepresentation(thumbImage, 1.0f);
[thumbData writeToFile:imagePath atomically:YES];
NSString *query_insert=[NSString stringWithFormat:#"Insert into UserDetails(User_id,User_fname,User_lname,User_image) values(%d,'%#','Smith','%#')",newid,VcAddUser.txtFUsername.text,relativePathImage1];
NSMutableArray *userData=[[NSMutableArray alloc]init];
userData=[[myDatabase executeQuery:query_insert];
[database close];
For Delete query:
NSString *query_user=[NSString stringWithFormat:#" delete from UserDetails where User_id=%d",Userid];
[myDatabase executeNonQuery:query_user];
[myDatabase close];
**For Update query:**
NSString *updatequery=[NSString stringWithFormat:#"Update UserDetails set User_fname='%#',User_lname='%#', User_image='%#' where User_id=%d",txtFUsername.text,txtLUsername.text,relativePathImage1,UseridUpdate];
[myDatabase executeNonQuery:updatequery];
// NSLog(#"Query user is %#",updatequery);
[myDatabase close];
For Webservices
-(void) CallWebservice
{
NSMutableData *responseData = [NSMutableData data];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"give your web service url"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:[requestString dataUsingEncoding:NSUTF8StringEncoding]];
NSURLConnection *PostConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[responseData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[responseData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
[self removeProgressIndicator];
UIAlertView *alt=[[UIAlertView alloc]initWithTitle:#"Internet connection is not Available!" message:#"Check your network connectivity" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alt show];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
// check for response only
/*NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"%#",responseString);*/
NSError *error;
NSDictionary *results = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
NSLog(#"%#",results);
}

how to add values from nsstrings in iOS?

I have 5 buttons. Each button has some value like 1,2,3,4,5 in a string named totalSeats_selected.
I want to save them into a nsstringthat shows result like this:
nsstring * result = [1,2,3,4,5];
These values are to used as request for a web service, so it must be in this format to send total number of seats?
So, how to save all these values in nsstring on button event?
Use like this.Suppose your string is in integer means use Method 1 .otherwise use Method 2(If your value assigned in NSString).
Method 1:
- (IBAction)Savebtnpressed:(id)sender {
NSMutableDictionary *datadict=[NSMutableDictionary dictionary];
[datadict setValue:[NSNumber numberWithInt:[first intValue]] forKey:#"1"];
[datadict setValue:[NSNumber numberWithInt:[second intValue]] forKey:#"2"];
[datadict setValue:[NSNumber numberWithInt:[third intValue]] forKey:#"3"];
[datadict setValue:[NSNumber numberWithInt:[fourth intValue]] forKey:#"4"];
[datadict setValue:[NSNumber numberWithInt:[fifth intValue]] forKey:#"5"];
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:datadict options:kNilOptions error:nil];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
NSURL *someURLSetBefore =[NSURL URLWithString:#" url "];
[request setURL:someURLSetBefore];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
// [request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
// [request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setHTTPBody:jsonData];
NSError *error;
NSURLResponse *response;
NSData *responseData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString * string1=[[NSString alloc]initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"%#",string1);
}
}
Method 2:
- (IBAction)Savebtnpressed:(id)sender {
NSMutableDictionary *datadict=[NSMutableDictionary dictionary];
[datadict setObject:[NSString stringWithFormat:#"%#",FIRST] forKey:#"1"];
[datadict setObject:[NSString stringWithFormat:#"%#",SECOND] forKey:#"2"];
[datadict setObject:[NSString stringWithFormat:#"%#",THIRD] forKey:#"3"];
[datadict setObject:[NSString stringWithFormat:#"%#",FOURTH] forKey:#"4"];
[datadict setObject:[NSString stringWithFormat:#"%#",FIFTH] forKey:#"5"];
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:datadict options:kNilOptions error:nil];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
NSURL *someURLSetBefore =[NSURL URLWithString:#" url "];
[request setURL:someURLSetBefore];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
// [request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
// [request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setHTTPBody:jsonData];
NSError *error;
NSURLResponse *response;
NSData *responseData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString * string1=[[NSString alloc]initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"%#",string1);
}
}

how to set background color of range in TTTAtributedLabel

Can't figure out how to set the background color of a range to make it look like a highlighter
The yellow color below does not show up as the background color
NSArray *keys = [[NSArray alloc] initWithObjects:(id)kCTForegroundColorAttributeName,(id)kCTUnderlineStyleAttributeName, (id) NSBackgroundColorAttributeName, nil];
NSArray *objects = [[NSArray alloc] initWithObjects:[UIColor redColor],[NSNumber numberWithInt:kCTUnderlineStyleNone], [UIColor yellowColor], nil];
NSDictionary *linkAttributes = [[NSDictionary alloc] initWithObjects:objects forKeys:keys];
self.madLibLabel.linkAttributes = linkAttributes;
[self.madLibLabel addLinkToURL:[NSURL URLWithString:#"what://"] withRange:[self.madLibLabel.text rangeOfString:#"WHAT"]];
You should use kTTTBackgroundFillColorAttributeName key instead NSBackgroundColorAttributeName.
Here is the code snippet:
NSArray *keys = [[NSArray alloc] initWithObjects:(id)kCTForegroundColorAttributeName,(id)kCTUnderlineStyleAttributeName, (id) kTTTBackgroundFillColorAttributeName, nil];
NSArray *objects = [[NSArray alloc] initWithObjects:[UIColor redColor],[NSNumber numberWithInt:kCTUnderlineStyleNone], [UIColor yellowColor], nil];
NSDictionary *linkAttributes = [[NSDictionary alloc] initWithObjects:objects forKeys:keys];
self.madLibLabel.linkAttributes = linkAttributes;
[self.madLibLabel addLinkToURL:[NSURL URLWithString:#"what://"] withRange:[self.madLibLabel.text rangeOfString:#"WHAT"]];

how to pass image to a web service in string format from xcode

+(id)profilePictureUploadWebService :(NSString*)temp andimage:(NSString*)strimage
{
//NSString *post=[NSString stringWithFormat:#"_UserId=%#&_UserImage=%#",temp,strimage];
NSString *post=#"";
NSString *urlTotal= [ NSString stringWithFormat:#"http://mo.sale.com/as.asmx/SaveUserImage?_UserId=%#&_UserImage=%#",temp,strimage];
NSURL *url= [ NSURL URLWithString:urlTotal];
NSLog(#"urlTotal is =%#",url);
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:url];
[request setHTTPMethod:#"GET"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"text/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSError *error;
NSURLResponse *response;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *data=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(#"data is =%#",data);
return (urlData);
}

How to add NavigationController into Tabbed Based Application in iOS

I'm using Xcode 4.4.1. I have created a simple tabbed based application. And then I want to add navigation controller to the application. Can any one tell me how to do that in Xcode 4.4.1. My current code is like this but it doesn't work.
`
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Override point for customization after application launch.
UIViewController *viewController1 = [[FirstViewController alloc] initWithNibName:#"FirstViewController" bundle:nil];
UIViewController *viewController2 = [[Addbills alloc]initWithNibName:#"Addbills" bundle:nil];
UIViewController *viewController3 = [[CalenderView alloc]initWithNibName:#"CalenderView" bundle:nil];
UIViewController *viewController4 = [[Web alloc]initWithNibName:#"Web" bundle:nil];
UIViewController *viewController5 = [[SecondViewController alloc] initWithNibName:#"SecondViewController" bundle:nil];
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
self.navigationController = [[UINavigationController alloc] initWithRootViewController:viewController1];
[self.navigationController setNavigationBarHidden:TRUE];
self.tabBarController = [[UITabBarController alloc] init];
self.tabBarController.viewControllers = #[viewController1,viewController2,viewController3,viewController4,viewController5];
self.window.rootViewController = self.tabBarController;
// self.window.rootViewController =self.navigationController;
[self.window addSubview:navigationController.view];
[self.window makeKeyAndVisible];
return YES;
}
`
and this is my button click event in viewController5
`
- (IBAction)backToPrevious:(id)sender {
[self.navigationController popToRootViewControllerAnimated:TRUE];
}`
Thanks,
Here is how you should do it.
// initialize the tabbar controller
UITabBarController *tabbarController = [[[UITabBarController alloc] init] autorelease];
UIViewController *itemsViewController1 = [[[UIViewController alloc] initWithNibName:#"SomeViewController1" bundle:nil] autorelease];
UINavigationController *itemsNavigationController1 = [[UINavigationController alloc] initWithRootViewController:itemsViewController1];
UIViewController *itemsViewController2 = [[[UIViewController alloc] initWithNibName:#"SomeViewController2" bundle:nil] autorelease];
UINavigationController *itemsNavigationController2 = [[UINavigationController alloc] initWithRootViewController:itemsViewController2];
tabbarController.viewControllers = #[itemsNavigationController1,itemsNavigationController2];
_window.rootViewController = tabbarController;

Resources