目前我正在为我的 iOS 应用程序编写一个在线登录,我对应该使用什么库来处理 HTTP-Request 和 XML-Parsing 进行了一些研究。我最终选择了 AFNetworking 和 KissXML。我还将 KissXML 添加用于 AFNetworking。对网站的请求成功,但我有点卡在解析收到的 XML 上。
响应如下所示:
<login>
<response status="success" result="correct"/>
<data>
<username>testusername</username>
<country>Germany</country>
</data>
</login>
在我的代码中,我对网站执行 HTTPRequest 以接收 XML,然后尝试检查用户数据是否有效。如果它们有效,我想收到用户名和国家/地区等元素。但如果发生错误,我想把它还给我。到目前为止我的代码:
{
__block BOOL success = NO;
__block NSError *localerror = nil;
__block NSString *domain = @"de.FranzBusch.Searchlight.ErrorDomain";
//HTTP Request
NSURL *url = [NSURL URLWithString:@"http://www.example.de/login.php"];
AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL:url];
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
email, @"email",
password, @"password", nil];
NSMutableURLRequest *request = [client requestWithMethod:@"POST" path:@"" parameters:params];
//Parse XML-Response
AFKissXMLRequestOperation *operation = [AFKissXMLRequestOperation XMLDocumentRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, DDXMLDocument *XMLDocument)
{
NSArray *resultNodes = nil;
NSError *responseError = nil;
resultNodes = [XMLDocument nodesForXPath:@"//response" error:&responseError];
if (responseError || ([resultNodes count] != 1))
{
localerror = [NSError errorWithDomain:domain code:-101 userInfo:[self generateErrorDictionary:@"XMLError"]];
success = NO;
}
else
{
for (DDXMLElement *element in resultNodes)
{
DDXMLNode *node = [element attributeForName:@"status"];
NSString *status = [node stringValue];
if ([status isEqualToString:@"fail"])
{
success = NO;
localerror = [NSError errorWithDomain:domain code:-101 userInfo:[self generateErrorDictionary:[[element attributeForName:@"result"] stringValue]]];
}
else
{
NSError *usernameError = nil;
NSArray *dataNodes = [XMLDocument nodesForXPath:@"//data//username" error:&usernameError];
if (usernameError || ([dataNodes count] != 1))
{
localerror = [NSError errorWithDomain:domain code:-101 userInfo:[self generateErrorDictionary:@"XMLError"]];
success = NO;
}
else
{
for (DDXMLELement *dataElement in dataNodes)
{
}
}
}
}
}
}failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, DDXMLDocument *XMLDocument)
{
NSLog(@"failure");
}];
[operation start];
return success;
}
谁能给我一个关于如何改进代码以及如何正确执行的提示。因为如果我想将 localerror 分配给错误,我总是会得到一个错误:(