简体   繁体   中英

How to download xml file and save in local iphone application

I have a magazine application i want that it load file from server and store it in application when application starts first time only and then use that locally file to save time i am getting data which is located on server it takes alot time

     NSURL*myurl=url; 

      myurl = [myurl stringByReplacingOccurrencesOfString:@"\n" withString:@""];
     myurl = [myurl stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]; 



     NSURL*urlloaded= [[NSURL alloc]initWithString:myurl];

    //NSURL*url= [[NSURL alloc]initWithString:@"http://localhost:8888/RowOne.xml"];

    NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithContentsOfURL:urlloaded];

//Initialize the delegate.

     RowTwoParser *parser = [[RowTwoParser alloc] initXMLParser];

//Set delegate

     [xmlParser setDelegate:parser];   
    BOOL success = [xmlParser parse];

  if(success)

  NSLog(@"No Errors");

   else

   NSLog(@"Error Error Error!!!");

You can download the initial data ie the XML file by using something like this

- (void)downloadInitialData {
    NSUserDefaults* userDefaults =  [NSUserDefaults standardUserDefaults];
    if ([userDefaults boolForKey:@"DATA_DOWNLOAD_KEY"] == NO) {
        [self showWaitViewWithText:@"Downloading Data..."];
        [self fetchDataFromServer];
    }
}



- (void)fetchDataFromServer {

    //Call to server to downlaod data
    //When Data is successfully downloaded

    //Stop loading when data save completes
    [self stopLoading];

    //Update USerDefaults
    NSUserDefaults* userDefaults =  [NSUserDefaults standardUserDefaults];
    [userDefaults setBool:YES forKey:@"DATA_DOWNLOAD_KEY"];
    [userDefaults synchronize];
}

You can make call to [self downloadInitialData]; which will ensure that Data is downloaded only once when the application starts . You will have to fix it according to your requirements to download data by resetting the @"DATA_DOWNLOAD_KEY" key.

What you can do is:-

Suppose you have parsed your xml and stored data in array say ' dataArray '

Now you have to save your dataArray in NSUserDefaults

NSUserDefaults *pref1=[NSUserDefaults standardUserDefaults];
[pref1 setObject:dataArray forKey:@"parseData"];    
[pref1 synchronize];

Whenever you have to use this data you can extract it like:-

NSUserDefaults *pref1=[NSUserDefaults standardUserDefaults];
NSArray *dataArray=[pref1 objectForKey:@"parseData"];

查看Apples自己的SeismicXML示例 - 可用的源代码。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM