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

Ios 如何将数据库和Nsxmlparser添加到应用程序中?,ios,nsxmlparser,Ios,Nsxmlparser,我想从webservice获取数据并将其显示在数据库中。要从webservice获取数据,必须首先使用ASIHTT连接委托与webservice使用连接委托建立连接。当建立连接并收到数据时,您需要使用nsxmlparserDelegate解析该数据,然后您可以将该数据存储到数据库中 -(void) request:(XMLRPCRequest *)request didReceiveResponse:(XMLRPCResponse *)response{ } -(void) request:(

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

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

-(void) request:(XMLRPCRequest *)request didReceiveResponse:(XMLRPCResponse *)response{  }
-(void) request:(XMLRPCRequest *)request didFailWithError:(NSError *)error{  }
对于解析,有三种委托方法:

1. didstartelement 
2. didendelement  
3. found character

仔细阅读,您就可以得到您的解决方案。

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

  • SQLite

  • 核心数据(最佳数据)指的是苹果的


  • 我同意Vijay的观点,在完成Vijay指定的步骤后,您必须使用核心数据概念,包括NSManagedObjectContext和更多。NSManagedObjectContext的行为就像一个便笺簿,您必须在XCDataModel文件中添加实体及其属性。完成此操作后,您必须单击新文件,XCode将自动创建两个扩展名为.h和.m的实体名文件。现在,您可以将XMl解析得到的任何数据输入实体的属性,最重要的是不要忘记保存现在,如果您想查看数据库的提要内容,可以使用Sqlite浏览器。在Sqlite浏览器中,您可以导入Sqlite文件,该文件将在运行应用程序时创建


    我想经过一些研究之后,您将能够做到这一点,如果您发现任何问题,我可以为您提供一个简单的核心数据基础示例代码。谢谢。

    好的,我将向您提供我在项目中使用的示例代码。。 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
    
    导入
    
    @接口RootViewController:UIViewControllerSoap消息应为:

    NSString *soapMsg=[NSString stringWithFormat:@""
    <"?xml version=\"1.0\" encoding=\"utf-8\"?>"];
    
    NSString*soapMsg=[NSString stringWithFormat:@]
    
    我想发布我在开发过程中使用的数据库类:

    -(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);
    
    }
    

    顺便说一句:
    [tempStr retainCount]>0
    完全是胡说八道。