获取损坏的XML,然后从webservice获取完整的XML

时间:2010-07-14 11:04:21

标签: iphone xml nsurlconnection

在我的联系人管理应用程序中,我使用webservice来获取包含联系人详细信息的大型xml数据。我使用NSURLConnection类发送请求。但是我在获取XML时遇到了问题。首先,我得到一个破碎的XML,然后我得到了整个XML数据。任何人都可以弄清楚我的应用程序出了什么问题。这是我正在使用的代码片段。

NSData *postData = [postFields dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d",[postData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:[[NSString alloc] initWithString:Url]]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Current-Type"];
[request setHTTPBody:postData];
conn = nil;
conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[myData appendData:data];

NSString *theXml = [[NSString alloc] initWithData:myData encoding:NSASCIIStringEncoding];

UIAlertView *thealert = [[UIAlertView alloc] initWithTitle:@"the xml" message:theXml delegate:self cancelButtonTitle:@"ok" otherButtonTitles:nil];
[thealert show];
[thealert release];

NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithData:data];
[xmlParser setDelegate:self];
[xmlParser parse];
    [xmlParser release];        
}

1 个答案:

答案 0 :(得分:3)

首先,您真的应该阅读Using NSURLConnection中的URL Loading System Programming Guide

要点是,connection:didReceiveData:可能(并且通常会)被多次调用,因此您应该在connectionDidFinishLoading:中进行所有处理。