如何将数据库和Nsxmlparser添加到应用程序中?

时间:2011-04-01 03:56:40

标签: ios nsxmlparser

我想从webservice获取数据,并希望将其显示在数据库中。

6 个答案:

答案 0 :(得分:0)

要从webservice获取数据,您必须首先使用 asiHttp 连接委托与使用连接委托的webservice建立连接。当连接建立和数据到来时,您需要使用nsxmlparserDelegate解析该数据,然后您可以将该数据存储到数据库中。

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

对于解析,有三种委托方法:

1. didstartelement 
2. didendelement  
3. found character

通过它,你得到了解决方案。

答案 1 :(得分:0)

要了解如何从网络服务和NSXMLParser获取数据,请搜索解析XML文件以了解如何通过xml获取数据并显示或使用数据进一步。当您获得该数据时,您可以非常轻松地将数据保存到数据库中,但这取决于您使用的是哪个数据库。那你有两个选择:

  1. SQLite的

  2. 核心数据(最佳)参考Apple的coreDataBooks

答案 2 :(得分:0)

我同意Vijay,在完成Vijay指定的步骤后,你必须使用核心数据概念,其中包括NSManagedObjectContext等等.NSManagedObjectContext的行为就像一个便笺簿,你必须在XCDataModel文件中添加实体及其属性执行此操作后,您必须单击新文件,XCode将自动创建两个扩展名为.h和.m的实体名称的文件。现在,无论您从XMl解析到实​​体的属性还是一个最重要的事情,您都可以提供数据。不要忘记保存它。现在如果你想看看你有什么提供给数据库你可以使用Sqlite浏览器。在sqlite浏览器中你可以导入sqlite文件,它将在你运行你的应用程序时创建。

我认为经过一些研究你可以做到这一点,如果你发现任何问题,我可以为你提供一个简单的核心数据基本示例代码。谢谢。

答案 3 :(得分:0)

肥皂消息应该是这样的:

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

答案 4 :(得分:-1)

好的,我将为您提供我在项目中使用的示例代码。 实施.h文件

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

答案 5 :(得分:-1)

我想发布我在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);

}