将XML文件从服务器复制到iphone?
问题描述:
我想从服务器复制xml文件以将它保存到本地,因为如果我将一次又一次地向服务器发送请求,则需要时间,所以我想在应用程序启动时将xml复制到本地资源,然后解析当地的xml,将XML文件从服务器复制到iphone?
我该怎么办?
答
首先你需要下载的文件:
NSURL *url = [NSURL URLWithString:FILEURL];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[NSURLConnection connectionWithRequest:request delegate:self];
然后添加在.h文件:
NSMutableData *receivedData;
,并在M档:
-(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
if (receivedData)
{
[receivedData appendData:data];
}
else
{
receivedData = [[NSMutableData alloc] initWithData:data];
}
}
-(void) connectionDidFinishLoading:(NSURLConnection *)connection
{
//saving your data in the local
NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *fullName = [NSString stringWithFormat:@"xmlfile.xml"];
NSString *fullFilePath = [NSString stringWithFormat:@"%@/%@",docDir,fullName];
[receivedData writeToFile:fullFilePath atomically:YES];
}
编辑: 从本地获取文件 -
NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *fullName = [NSString stringWithFormat:@"xmlfile.xml"];
NSString *fullFilePath = [NSString stringWithFormat:@"%@/%@",docDir,fullName];
NSData *myData = [NSData dataWithContentsOfFile:filePath];
现在你可以在解析NSData的时候,网站上有很多例子。
你是为WebKit还是Cocoa应用编码? – Alex
Cocoa app @Alex –
为什么你需要复制XML文件?它暗示它或者不会改变(所以你只是将它捆绑在应用程序中),或者它不会像你轮询服务器那样频繁改变(所以轮询更少)。 – Alex