在单独的线程上加载XML文件,覆盖旧的并保存

时间:2010-03-27 06:48:28

标签: iphone iphone-sdk-3.0

更新11/18/2011 检查接受的答案。它有效并且可以节省生命!

嘿大家......所以我想弄清楚如何做到这一点。我已经在很多论坛上反弹试图找到我的答案,但没有成功。他们的过程对我来说太复杂了,或者只是矫枉过正。我想要做的就是这个。我的应用程序中有一个XML文件。它是一个500k xml文件,我不希望用户在加载时必须等待。所以...我把它放在我的应用程序中,这会导致加载时间过长,并使应用程序脱机使用。我想要做的是,当应用程序加载时,在后台(单独的线程)下载可能用新数据更新的SAME xml文件。一旦xml​​文件完成,我想要REPLACE用于加载文件的xml文件。任何建议或代码提示将不胜感激。提前谢谢!

3 个答案:

答案 0 :(得分:2)

您可以使用NSOperation异步下载文件。

您可以使用NSFileManager将文件保存到应用程序的Documents目录。

编辑:

您正在尝试写入应用程序包中的文件。您无法写入捆绑包中的任何文件 - 它是Apple安全沙箱模型的一部分。

您应该将文件放在应用程序的Documents目录中并在那里写入。

NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* documentsDirectoryPath = [paths objectAtIndex:0];
NSString* filePath = [documentsDirectoryPath stringByAppendingPathComponent:@"myfile.xml"];

答案 1 :(得分:0)

您是否可以控制服务器上的XML?不是下载XML文件,而是它是否不同,请创建该文件的SHA1签名,并将其与已缓存的文件的SHA1签名进行比较。

如果签名相同,则无需为用户增加第二次无意义下载(特别是在WWAN网络上)。如果签名不同,那么您才会在后台触发下载请求。

答案 2 :(得分:0)

我最终搞清楚了。这是一个古老的帖子,但它似乎仍然有很多观点,所以我想我会帮助一些人。请记住,这段代码并不完美...有很多方法可以给猫皮肤涂抹......这就是我剥皮的方法。这很有用,这就重要了!

简而言之,它的工作原理是...... 该应用程序启动>检查是否有保存的“日期/ ID”。它的格式为“MMDD”。如果没有保存的日期/ ID,它将创建一个空白的日期/ ID以便稍后进行比较。

当比较id是否匹配时,它将下载一个新文件。 今天的日期是11/18/2011,所以ID为“1118”。如果您今天再次启动应用程序,ID将匹配,因此应用程序将解析本地xml文件而不是下载另一个。 (对我来说,它节省了大量时间,我的XML文件是2-4 mbs。)

此代码每天都会下载一个新的xml文件,除非该应用程序已经运行了一天。然后它将使用本地文件。

//////////      applicationDidFinishLaunching     ///////////
lastSyncArray = [[NSMutableArray alloc] initWithCapacity:0];

//check documents directory to see if you have a saved "date/ID" from earlier
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDir = [paths objectAtIndex:0];
NSString *fullFileNameSavedLastSyncArray = [NSString stringWithFormat:@"%@/lastSyncArray", docDir];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:fullFileNameSavedLastSyncArray];

if (fileExists == YES) {
    // yes you have a saved "date/ID" from earlier
    NSArray * temp = [[NSArray alloc] init];
    temp = [NSKeyedUnarchiver unarchiveObjectWithFile:fullFileNameSavedLastSyncArray];

    for ( int i=0; i<[temp count]; i++ ){

        [lastSyncArray addObject:[temp objectAtIndex:i]];

    }// end for loop


}
else {

    //insert blank data for comparison later
    [lastSyncArray addObject:@""];
}

[NSThread detachNewThreadSelector:@selector(checkXMLFile) toTarget:self withObject:nil];

/////////// end applicationDidFinishLaunching /////////////




// own function in App Delegate
-(void)checkXMLFile {


    //get current month/day
    NSDateComponents *components = [[NSCalendar currentCalendar] components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit fromDate:[NSDate date]];
    NSInteger day = [components day];
    NSInteger month = [components month];
    NSString * currentTimeString = [NSString stringWithFormat:@"%d%d",month,day];


    //check if file exists first
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString * fileName = [NSString stringWithFormat:@"inventory.xml"];
    NSString *xmlPath = [documentsDirectory stringByAppendingPathComponent:fileName];
    BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:xmlPath];

    if (fileExists == YES) {
        //yes there is a saved xml file
        NSLog(@"There is a saved file from before");

        //compare last sync date and current date. if they mismatch... download new file
        NSString * sToCompare = [[lastSyncArray objectAtIndex:0] description];

        if ([sToCompare compare:currentTimeString]==0) {
            //its a match this has been downloaded today. no need to re download.
        }
        else {

            //clear out old download date and save new
            [lastSyncArray removeAllObjects];

            //save new date         
            [lastSyncArray addObject:currentTimeString];

            // we are downloading a new xml file and saving it
            NSString * pdfURL2 = [NSString stringWithFormat:@"http://myfile.com/inventory.xml"];
            NSString *urlString = pdfURL2;
            NSURL *url = [NSURL URLWithString:urlString];
            NSData * xmlData = [NSData dataWithContentsOfURL:url];

            if (!xmlData) {


            }
            else{
                NSLog(@"EXISTS");
                NSLog(@"Begin to save xml");
                NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
                NSString *documentsDirectory = [paths objectAtIndex:0];
                NSString * fileName = [NSString stringWithFormat:@"inventory.xml"];
                NSLog(@"File to save: %@",fileName);
                NSString *xmlPath = [documentsDirectory stringByAppendingPathComponent:fileName];
                [xmlData writeToFile:xmlPath atomically:YES];
                NSLog(@"XML saved");


            }
        }



    }
    else {
        NSLog(@"MISSING XML");
        //no there is not a saved xml file this must be first load go ahead and download
        NSString * pdfURL2 = [NSString stringWithFormat:@"http://myfile.com/inventory.xml"];
        NSString *urlString = pdfURL2;
        NSURL *url = [NSURL URLWithString:urlString];
        NSData * xmlData = [NSData dataWithContentsOfURL:url];

        if (!xmlData) {


        }
        else{
            NSLog(@"EXISTS");
            NSLog(@"Begin to save xml");
            NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
            NSString *documentsDirectory = [paths objectAtIndex:0];
            NSString * fileName = [NSString stringWithFormat:@"inventory.xml"];
            NSLog(@"File to save: %@",fileName);
            NSString *xmlPath = [documentsDirectory stringByAppendingPathComponent:fileName];
            [xmlData writeToFile:xmlPath atomically:YES];
            NSLog(@"XML saved");


        }
    }


    [self sendToParser];


}



- (void)sendToParser{

    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];


    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString * fileName = [NSString stringWithFormat:@"inventory.xml"];
    NSString *xmlPath = [documentsDirectory stringByAppendingPathComponent:fileName];

    [self parseXMLFileAtURL:xmlPath];

    [pool release];

}


- (void)parseXMLFileAtURL:(NSString *)URL //URL is the file path (i.e. /Applications/MyExample.app/MyFile.xml)
{   
    //you must then convert the path to a proper NSURL or it won't work
    NSURL *xmlURL = [NSURL fileURLWithPath:URL];
    NSData * data = [[NSData alloc] init];
    data = [NSData dataWithContentsOfURL:xmlURL];

    // here, for some reason you have to use NSClassFromString when trying to alloc NSXMLParser, otherwise you will get an object not found error
    // this may be necessary only for the toolchain
    NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data];

    // Set self as the delegate of the parser so that it will receive the parser delegate methods callbacks.
    [parser setDelegate:self];

    // Depending on the XML document you're parsing, you may want to enable these features of NSXMLParser.
    [parser setShouldProcessNamespaces:NO];
    [parser setShouldReportNamespacePrefixes:NO];
    [parser setShouldResolveExternalEntities:NO];

    [parser parse];

    [parser release];
}




- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespace qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{

    //your code here
    return;

}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
    //your code here
}


- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespace qualifiedName:(NSString *)qName
{
    //your code here
    return;
}


- (void)parserDidEndDocument:(NSXMLParser *)parser{
    //your code here

}






//////////   application will terminate    /////////////
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDir = [paths objectAtIndex:0];
NSString *fullFileNameSavedLastSyncArray = [NSString stringWithFormat:@"%@/lastSyncArray", docDir];
NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL fileExists fileExists = [[NSFileManager defaultManager] fileExistsAtPath:fullFileNameSavedLastSyncArray];

//check to see we have a last sync array
fileExists = [[NSFileManager defaultManager] fileExistsAtPath:fullFileNameSavedLastSyncArray];
if (fileExists == YES) {
    //file exists delete it so we can recreate it here in a sec
    [fileManager removeItemAtPath:fullFileNameSavedLastSyncArray error:NULL];
}
if ([lastSyncArray count] >=1) {
    [NSKeyedArchiver archiveRootObject:lastSyncArray toFile:fullFileNameSavedLastSyncArray];
}


////// end application will terminate ///////////