将XML文件从Server复制到iphone?

时间:2011-10-04 08:04:44

标签: iphone

我想从服务器复制xml文件以将其保存到本地,因为如果我一次又一次地向服务器发送请求,则需要时间,所以我想在应用启动时将xml复制到本地资源,然后解析本地xml,

我该怎么办?

1 个答案:

答案 0 :(得分:1)

首先,您需要下载文件:

    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,网站上有很多例子。