How to add database and Nsxmlparser into applicati

2019-09-21 02:16发布

问题:

I want to fetch data from webservice and want to display it in to database.

回答1:

I am agree with Vijay, After doing the steps specified by Vijay you have to use core data concepts,which includes NSManagedObjectContext and many more.NSManagedObjectContext behaves like just a scratch pad,you have to add entities and their attributes in XCDataModel file.After doing this you have to click on new file and XCode will automatically create two files with extension .h and .m of your entity name.Now you can feed data whatever you are getting from XMl parsing into entity's attributes and one most important thing don't forget to save it.And now if you want to see what you have feed to database you can use Sqlite browser.In sqlite browser you can import sqlite file which will be created when you run your application.

I think after some study you will be able to do this ,if you find any problem I can provide you a simple core data fundamental sample code.Thanks.



回答2:

For getting data from webservice you have to first establish connection using asiHttp connection delegate with the webservice using connection delegate. And when connection establish and data comes you need to parse that data using nsxmlparserDelegate and then you can store that data into database.

-(void) request:(XMLRPCRequest *)request didReceiveResponse:(XMLRPCResponse *)response{  }
-(void) request:(XMLRPCRequest *)request didFailWithError:(NSError *)error{  }

For parsing there are three delegate method:

1. didstartelement 
2. didendelement  
3. found character

Go through it and you get your solution.



回答3:

Soap message should be this:

NSString *soapMsg=[NSString stringWithFormat:@""
<"?xml version=\"1.0\" encoding=\"utf-8\"?>"];


回答4:

In order to know how to fetch the data from web service and NSXMLParser please search for Parsing XML Files to know how to fetch the data through an xml and display it or use that data further. And when you will get that data you can save that data very easily to the database but it depends on you that which database you are using. Well you have two options:

  1. SQLite

  2. Core data (Best one) refer to Apple's coreDataBooks



回答5:

Ok i am going to provide you sample code that i used in my project.. implementation of .h file

import <"UIKit/UIKit.h>
import <"sqlite3.h>

@interface RootViewController : UIViewController<"UITableViewDelegate,UITableViewDataSource,NSXMLParserDelegate> 

{

IBOutlet UITableView *listtbl;
    NSString *databaseName;
    NSString *dbPath;
    NSString *id1;
    NSMutableArray *mainarray,*temparray;
    NSMutableDictionary *tempdic;

    NSMutableData *myWebData;
    NSXMLParser *myXMLParser;
    NSString *tempStr;

}
-(void)readdata;
-(void)checkdata;
-(void)savedata;
@end


.m file

import "RootViewController.h"


@implementation RootViewController




- (void)viewDidLoad
{
    [super viewDidLoad];
   databaseName=@"db1.sqlite3";
    temparray=[[NSMutableArray alloc]init];


    sqlite3 *database;

    [self checkdata];

    if(sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK)

    {
        NSString *str=[NSString stringWithFormat:@"delete from tbl"];

        const char *sqlStmt=[str UTF8String];

        sqlite3_stmt *cmp_sqlStmt;

        if(sqlite3_prepare_v2(database, sqlStmt, -1, &cmp_sqlStmt, NULL)==SQLITE_OK)
        {
            int returnValue = sqlite3_prepare_v2(database, sqlStmt, -1, &cmp_sqlStmt, NULL);
            ((returnValue==SQLITE_OK) ?  NSLog(@"Success") :  NSLog(@"UnSuccess") );
            sqlite3_step(cmp_sqlStmt);
        }
        sqlite3_finalize(cmp_sqlStmt);
    }

    sqlite3_close(database);



    NSString *soapMsg=[NSString stringWithFormat:@"<?xml version=\"1.0\"?><myXML>\n"
                       "<function>logincheck</function>\n"
                       "<values></values>\n"
                       "</myXML>"];

    NSURL *myurl=[NSURL URLWithString:@"http://demo/webservice/category_check.php"];


    NSMutableURLRequest *connectionReq=[NSMutableURLRequest requestWithURL:myurl];

    //<?xml version="1.0" encoding="utf-8"?>

    [connectionReq addValue:@"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];

    //[connectionReq addValue:@"http://www.webservicex.net/GetWeatherByZipCode" forHTTPHeaderField:@"SOAPAction"];

    [connectionReq setHTTPBody: [soapMsg dataUsingEncoding:NSUTF8StringEncoding]];

    [connectionReq addValue:[NSString stringWithFormat:@"%i",[soapMsg length]] forHTTPHeaderField:@"Content-Length"];

    [connectionReq setHTTPMethod:@"POST"];



    NSURLConnection *myConnection=[[NSURLConnection alloc] initWithRequest:connectionReq delegate:self];


    if (myConnection) {

        myWebData=[[NSMutableData alloc]initWithLength:0];
        mainarray=[[NSMutableArray alloc]init];


    }


    [super viewDidLoad];

}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error

{
    NSLog(@"connection error");
}


-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response

{

    [myWebData setLength:0];

}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data

{ 
    [myWebData appendData:data];

}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{

    NSLog(@"%@",[myWebData description]);

    NSString *str1=[[NSString alloc] initWithBytes:[myWebData bytes] length:[myWebData length] encoding:NSStringEncodingConversionAllowLossy];

    NSLog(@"%@",str1);

    [str1 release];


    if(myXMLParser!=nil && [myXMLParser retainCount]>0)

    {   
        myXMLParser.delegate=nil; 

        [myXMLParser release]; 

        myXMLParser=nil; 

    }
    myXMLParser=[[NSXMLParser alloc] initWithData:myWebData];

    myXMLParser.delegate=self;

    [myXMLParser parse];

}

-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict

{
    if ([elementName isEqualToString:@"ArrayOfconsumer"]) {

    }
    if ([elementName isEqualToString:@"data"]) {

        tempdic=[[NSMutableDictionary alloc]init];
    }


} 

-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string

{
    if(tempStr!=nil && [tempStr retainCount]>0)

    {  
        [tempStr release]; tempStr=nil;

    }

    tempStr=[[NSString alloc] initWithString:string];

}


-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName

{

    if ([elementName isEqualToString:@"data"]) {
        [mainarray addObject:tempdic];
        [tempdic release];
    }

    if ([elementName isEqualToString:@"catid"]) {
        [tempdic setObject:tempStr forKey:elementName];
    }

    if ([elementName isEqualToString:@"cat_name"]) {
        [tempdic setObject:tempStr forKey:elementName];
    }

    if ([elementName isEqualToString:@"image"]) {

        [tempdic setObject:tempStr forKey:elementName];
    }

    if ([elementName isEqualToString:@"has_subcategory"]) {

        [tempdic setObject:tempStr forKey:elementName];
    }



}   

- (void)parserDidEndDocument:(NSXMLParser *)parser

{
    NSLog(@"mainarray=====%@",[mainarray description]);

    [self savedata];

    [self readdata];

    [listtbl reloadData];

    //[progressAlert dismiss];
} 

-(void)checkdata
{

    NSArray *docPaths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);

    NSString *docDir=[docPaths objectAtIndex:0];

    dbPath=[docDir stringByAppendingPathComponent:databaseName];

    BOOL success;

    NSFileManager *fm=[NSFileManager defaultManager];

    success=[fm fileExistsAtPath:dbPath];

    if(success) return;

    NSString *dbPathFromApp=[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:databaseName];

    [fm copyItemAtPath:dbPathFromApp toPath:dbPath error:nil];

    [fm release];


}

-(void)savedata

{
    sqlite3 *database;

    [self checkdata];

    if(sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK)
    {
        NSString *sqlTmp=[NSString stringWithFormat:@"insert into tbl values(NULL,'%@','%@')",[[mainarray objectAtIndex:0]valueForKey:@"catid"],[[mainarray objectAtIndex:0]valueForKey:@"image"]];

        const char *sqlStmt=[sqlTmp UTF8String];

        sqlite3_stmt *cmp_sqlStmt;

        int returnValue = sqlite3_prepare_v2(database, sqlStmt, -1, &cmp_sqlStmt, NULL);

        ((returnValue==SQLITE_OK) ?  NSLog(@"Success") :  NSLog(@"UnSuccess") );


        sqlite3_step(cmp_sqlStmt);

        sqlite3_finalize(cmp_sqlStmt);

    }

    sqlite3_close(database);



}

-(void)readdata

{
    [self checkdata];

    sqlite3 *database;



    if(sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK)

    {
        NSString *sql=[NSString stringWithFormat:@"select * from tbl"];

        const char *sqlStmt=[sql UTF8String];

        sqlite3_stmt *cmp_sqlStmt; 

        if(sqlite3_prepare_v2(database, sqlStmt, -1, &cmp_sqlStmt, NULL)==SQLITE_OK)

        {
            while(sqlite3_step(cmp_sqlStmt)==SQLITE_ROW)
            {
                id1=[NSString stringWithUTF8String:(char*)sqlite3_column_text(cmp_sqlStmt, 2)];

                //newStu=[[student alloc]initWithNo:id1];

                [temparray addObject:id1];

                //[newStu release];


            }
        }

        sqlite3_finalize(cmp_sqlStmt);

    }

    sqlite3_close(database);
}



// Customize the number of sections in the table view.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return [temparray count];

}


// Customize the appearance of table view cells.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }

    cell.textLabel.text=[temparray objectAtIndex:indexPath.row];
    // Configure the cell.


    return cell;

}








- (void)dealloc {
    [super dealloc];
}


@end


回答6:

I would like to post my database classes that i used during developmaent:

-(void)check_Create_DB
{
    NSArray *docPaths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);

    NSString *docDir=[docPaths objectAtIndex:0];


    dbPath=[docDir stringByAppendingPathComponent:databaseName];

    BOOL success;

    NSFileManager *fm=[NSFileManager defaultManager];

    success=[fm fileExistsAtPath:dbPath];

    if(success) return;

    NSString *dbPathFromApp=[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:databaseName];
    [fm copyItemAtPath:dbPathFromApp toPath:dbPath error:nil];

    [fm release];

}

-(void)saveData;

{

sqlite3 *database;

    [self check_Create_DB];

    if(sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK)
    {
        NSString *sqlTmp=[NSString stringWithFormat:@"insert into  AddEmployeeDetails values(NULL,'%@', '%@','%@', '%@', '%@', '%@', '%@', '%@','%@','%@','%@')",[txtempname text],[txtadd text],[txtcountry text],[txtstate text],[txtcity text],[txtcontactno text],[txtqualification text],[txtshift text],[txtposition text],[txtjoindate text],[txtsalary text]];

        const char *sqlStmt=[sqlTmp UTF8String];

        sqlite3_stmt *cmp_sqlStmt;

        int returnValue = sqlite3_prepare_v2(database, sqlStmt, -1, &cmp_sqlStmt, NULL);

        //((returnValue==SQLITE_OK) ?  NSLog(@"Success") :  NSLog(@"UnSuccess") );
        if (returnValue==SQLITE_OK) {
            temp=2;
            NSLog(@"Success");
        }
        else {
            temp=1;
            NSLog(@"Unsuccess");
        }

        sqlite3_step(cmp_sqlStmt);
        sqlite3_finalize(cmp_sqlStmt);
    }

    sqlite3_close(database);    
}

-(void)getDataFromTb  
{

[self checkAndCreateDatabase];

sqlite3 *database;

mainDataArray=[[NSMutableArray alloc] init];

if (sqlite3_open([databasePath UTF8String], &database)==SQLITE_OK) 

{

NSString *sql=[NSString stringWithFormat:@"select * from AlarmTbl"];

const char *sqlStatement = [sql UTF8String];

sqlite3_stmt *compiledStatement;

if (sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL)==SQLITE_OK) 

{

while(sqlite3_step(compiledStatement) == SQLITE_ROW) {

NSMutableDictionary *item=[[NSMutableDictionary alloc] init];

[item setObject:[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 0)] forKey:@"Id"];
char *ttl=(char *)sqlite3_column_text(compiledStatement, 1);

if (ttl==NULL) {

[item setObject:@"" forKey:@"title"];

}

else {

[item setObject:[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)] forKey:@"title"];

}

char *dttim=(char *)sqlite3_column_text(compiledStatement, 2);

if (dttim==NULL) {

[item setObject:@"" forKey:@"datetime"];

}
else {

[item setObject:[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 2)] forKey:@"datetime"];

}

char *enbl=(char *)sqlite3_column_text(compiledStatement, 3);

if (enbl==NULL) {

[item setObject:@"" forKey:@"enabled"];

}
else {

[item setObject:[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 3)] forKey:@"enabled"];

}

[mainDataArray addObject:item];

}

}

sqlite3_finalize(compiledStatement);

}

sqlite3_close(database);

}