0

目前我正在为我的 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 分配给错误,我总是会得到一个错误:(

4

1 回答 1

2

如果我对您的理解正确,那么您在解析 XML 响应时遇到了问题。我通常只使用 Apple 的流 XML 解析器 NSXMLParser。它简单、快速且易于使用。

我为您做了一个小示例项目(使用 ARC),使用 NSXMLParser 解析您描述的 XML 响应:https ://github.com/erikt/ETXMLParseSOExample

您可以使用它并运行项目,但重要的部分是 NSXMLParser 委托:

@interface ETLoginInfoXMLParser ()
@property (strong,nonatomic) NSMutableString *currentElementValue;
@property (strong,nonatomic) ETLoginInfo *loginInfo;
@end

@implementation ETLoginInfoXMLParser

#pragma mark - NSXMLParserDelegate
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
    if ([elementName isEqualToString:@"login"]) {
        if (!self.loginInfo) {
            self.loginInfo = [[ETLoginInfo alloc] init];
        }
        return;
    }
    
    if ([elementName isEqualToString:@"response"]) {
        self.loginInfo.responseStatus = [attributeDict objectForKey:@"status"];
        self.loginInfo.responseResult = [attributeDict objectForKey:@"result"];
    }
}

- (void) parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
    if (!self.currentElementValue) {
        self.currentElementValue = [[NSMutableString alloc] initWithString:string];
    } else {
        [self.currentElementValue appendString:string];
    }
}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
    if ([elementName isEqualToString:@"username"]) {
        NSString *trimmedValue = [self.currentElementValue stringByTrimmingCharactersInSet:
                                  [NSCharacterSet whitespaceAndNewlineCharacterSet]];
        self.loginInfo.username = trimmedValue;
    }
    
    if ([elementName isEqualToString:@"country"]) {
        NSString *trimmedValue = [self.currentElementValue stringByTrimmingCharactersInSet:
                                  [NSCharacterSet whitespaceAndNewlineCharacterSet]];
        self.loginInfo.country = trimmedValue;
    }
    
    self.currentElementValue = nil;
}


/** Parse XML login response */ 
+(ETLoginInfo *)parseXMLLoginResponse:(NSString *)xml {
    ETLoginInfoXMLParser *loginInfoParser = [[ETLoginInfoXMLParser alloc] init];
    NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithData:[xml dataUsingEncoding:NSUTF8StringEncoding]];
    [xmlParser setDelegate:loginInfoParser];
    BOOL success = [xmlParser parse];
    
    if (success) {
        return loginInfoParser.loginInfo;
    } else {
        NSLog(@"Error parsing login information");
        return nil;
    }
}

@end

我将它连接到一个愚蠢的 iOS 应用程序以显示此 XML 响应的解析:

<login>
  <response status="success" result="correct"/>
  <data>
    <username>Willy Wonka</username>
    <country>Germany</country>
  </data>
</login>

在此处输入图像描述 在此处输入图像描述

你会想要一个更有趣的模型层次结构——为了简单起见——只是把所有东西放在同一个实体中

于 2012-11-06T20:17:52.673 回答