如何将数据库和Nsxmlparser添加到应用程序中?
用于从获取数据您必须首先建立连接,使用asiHttp连接代理与webservice
使用连接代理。当连接建立和数据到达时,您需要使用nsxmlparserDelegate
解析该数据,然后可以将该数据存储到数据库中。
-(void) request:(XMLRPCRequest *)request didReceiveResponse:(XMLRPCResponse *)response{ }
-(void) request:(XMLRPCRequest *)request didFailWithError:(NSError *)error{ }
对于分析有三种委托方法:
1. didstartelement
2. didendelement
3. found character
通过它,你会得到您的解决方案。
@rio为了解如何从网络服务获取数据和NSXMLParser
请参考Parsing XML Files,在这里您将能够知道他们如何通过Books.xml
获取数据并进一步显示或使用该数据。当你得到这些数据时,你可以很容易地将这些数据保存到数据库中,但是这取决于你使用哪个数据库。那么你有两个选择....
1.SQLite参考here
2.Core数据(最好的)是指coreDataBooks
祝您好运!
我同意Vijay,在完成Vijay指定的步骤之后,您必须使用核心数据概念,其中包括NSManagedObjectContext等等.NSManagedObjectContext的行为就像是一个便笺簿,您必须在XCDataModel中添加实体及其属性file.After这样做后,你必须点击新文件,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];
[email protected]"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
顺便说一下:'[tempStr retainCount]> 0'是完全废话。 – bbum 2011-04-01 17:54:50
SOAP消息应该是这样的:
NSString *soapMsg=[NSString stringWithFormat:@""
<"?xml version=\"1.0\" encoding=\"utf-8\"?>"];
我想后,我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);
}
这个答案有两个死链接,删除他们会使这种回答有些无用。你能修好它吗? – rene 2017-07-04 08:47:51