2011-10-15 58 views
1

我在本地保存了一个xml文件,并使用NSXmlParser(存储在Resource文件夹中)显示细节。但是,现在我想从url(从客户端)下载新的xml,并需要在本地存储新的xml文件,并且还需要从应用程序中删除现有的xml文件。我怎样才能做到这一点?有什么建议么?有任何示例代码/项目供参考?请帮帮我。感谢您阅读我可怜的英语。感谢提前。如何下载文件并保存在本地iphone应用程序中?

+2

你可以用ASIHTTPRequest做到这一点。我使用ASIHTTPRequest在iPhone中下载了30 MB zip文件,并在本地解压缩。 –

+0

非常感谢您的快速响应。我不太熟悉iPhone/iPad的开发。如果你不介意你能解释你的答案吗?谢谢。 –

回答

2

虽然你可以从文件目录或缓存目录中删除文件,但是我的方式是主要在应用程序目录上执行文件操作。

首先你会保存从应用程序资源的yr xml文件到缓存目录,然后从那里访问文件。并且你还可以从资源目录中删除文件,不再需要它。 在互联网上可用的任何新文件,然后首先从缓存中删除旧文件,并将新文件添加到缓存目录。

整个事情如下: -

//get your cachedirectory path 
NSArray *imagepaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES); 
NSString *cachdirectory = [[NSString alloc] initWithString:[imagepaths objectAtIndex:0]]; 

//first save your file from resource directory to app's cache directory 
NSString * path = [[NSBundle mainBundle] pathForResource:@"fileinresource" ofType:@"xml"]; 
NSData *filedata = [NSData dataWithContentsOfFile:path]; 
NSFileManager *fileManager = [NSFileManager defaultManager]; 
NSString *savename = [cachdirectory stringByAppendingPathComponent:@"mynewfile.xml"]; 
[fileManager createFileAtPath:savename contents:filedata attributes:nil];  

//remove file from resource directory 
[fileManager removeItemAtPath:path error:nil]; 

//new file from internet is avilable then do following:first remove old file from cache 
[fileManager removeItemAtPath:cachdirectory error:nil]; 

//save new file from internet 
NSData *newfiledata=[NSData dataWithContentsOfURL:[NSURL URLWithString:myxmlurlstringpath]]; 
[fileManager createFileAtPath:savename contents:newfiledata attributes:nil];   
+0

非常感谢您的快速响应。在ios开发中不太熟悉。这就是为什么我在每一个行动中挣扎。感谢您的回答。我将在我的代码中加入。谢谢。 –

相关问题