我想獲取來自Web服務的數據,並希望在顯示它DATABSE如何將數據庫和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);
}
- 1. 如何將SQLite數據庫添加到iOS(CoreData)應用程序?
- 2. 如何從Web應用程序添加到數據庫?
- 3. Erlang:將庫添加到應用程序
- 4. 將數據庫添加到mvc3應用程序時出錯
- 5. 將多個數據庫添加到單個Android應用程序
- 6. 將SQLite數據庫添加到iPhone應用程序
- 7. 無法將數據庫添加到Asp.Net應用程序
- 8. 如何將數據庫文件附加到應用程序
- 9. 如何將可移植數據庫添加到MVC應用程序?
- 10. 如何將數據庫添加到擺動桌面應用程序
- 11. 外鍵添加到數據庫中的Rails應用程序
- 12. 如何將C,C++庫添加到我的j2ee應用程序
- 13. 如何將壁紙庫添加到Android應用程序
- 14. 數據庫如何加載到應用程序中?
- 15. 如何將數據庫添加到IList?
- 16. 如何在實現Forms安全的應用程序中將數據添加到數據庫中?
- 17. 將核心數據添加到我的iPhone應用程序中
- 18. 將數據添加到數據庫中
- 19. 將文件添加到Ruby on Rails應用程序中的數據庫?
- 20. 如何將System.Xml.XmlDocument類型添加到和應用程序狀態
- 21. 如何將選項和習俗添加到jQuery應用程序
- 22. 如何將數據添加到我的android應用程序中的現有數據庫?
- 23. 如何將用戶名和密碼添加到Firebase數據庫
- 24. 如何使用c#編程將數據添加到MSQL數據庫中?
- 25. 如何將「選擇數據源」添加到我的Excel應用程序中?
- 26. 如何在生產中將數據添加到rails應用程序?
- 27. 添加圖片到q測驗應用程序的數據庫
- 28. Laravel 5.2添加到數據庫後應用程序崩潰
- 29. Android:添加到應用程序數據庫不工作
- 30. 如何使用python將應用程序連接到數據庫?
這個答案有兩個死鏈接,刪除他們會使這種回答有些無用。你能修好它嗎? – rene 2017-07-04 08:47:51