iOS无法将URL内容存储到数组中

时间:2012-08-15 03:02:32

标签: iphone ios xml nsurlconnection

我必须连接到URL以检查记录是否为空。响应看起来像这样:

<?xml version = "1.0" encoding = "UTF-8"?>
<find>
<record_id>1234</record_id>
<no_record>00001</no_record>
<entry_num>00001</entry_num>
<session-id>aijheifaohqrihelrkqn324tlejaofjaf</session-id>
</find>

我的代码:

                NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init]
                                                autorelease];
                [request setURL:[NSURL URLWithString: finalSearchURL]];

                // Content-Type related.
                [request setValue:@"application/x-www-form-urlencoded"
               forHTTPHeaderField:@"Content-Type"];

                // Create Connection.
                NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];

                if (conn) {
                    // The connection was established.
                    NSMutableData *receivedData =  [[NSMutableData alloc] initWithContentsOfURL:[NSURL URLWithString:request]];
                    NSLog( @"Data will be received from URL: %@", request.URL );
                    NSLog(@"Recieved Data 2: %@", receivedData);
                }
                else
                {
                    // The download could not be made.
                    NSLog( @"Data could not be received from: %@", request.URL );
                }

但它让我回答:

Recieved Data : <3c3f786d 6c207665 7273696f 6e203d20 22312e30 2220656e 636f6469 6e67203d 20225554 462d3822 3f3e0a3c 66696e64 3e0a3c73 65745f6e 756d6265 723e3031 39303633 3c2f7365 745f6e75 6d626572 3e0a3c6e 6f5f7265 636f7264 733e3030 30303030 3030313c 2f6e6f5f 7265636f 7264733e 0a3c6e6f 5f656e74 72696573 3e303030 30303030 30313c2f 6e6f5f65 6e747269 65733e0a 3c736573 73696f6e 2d69643e 4d505843 33323433 58564336 4534454a 41464232 45473541 39374237 584e3832 43554631 4e314234 584e4c37 424c5947 4e533c2f 73657373 696f6e2d 69643e0a 3c2f6669 6e643e0a 20>

任何人都可以帮忙告诉我,我做错了什么?这是我第一次尝试从网址获取回复请帮助谢谢!

3 个答案:

答案 0 :(得分:0)

您使用的方法是从网址获取原始数据。您需要一个解析器将原始数据转换为可理解的结构(可能是NSDictionary而不是NSArray)。

Apple为您提供了NSXMLParser从网址中检索xml结构,或者您可以找到其他xml解析器库。

答案 1 :(得分:0)

实际上,您的代码正在返回正确的数据。由于NSData可以保存任何类型的数据,因此它只显示十六进制值。如果将十六进制数据转换为sting,您将看到它具有正确的文本。

现在,您的代码可以简化很多。根本不需要所有用于设置NSURLConnection的代码。您只需要以下几行。

NSString *recievedText = [NSString stringWithContentsOfFile:finalSearchURL encoding:NSUTF8StringEncoding error:NULL];

答案 2 :(得分:0)

以这种方式将数据视为字符串:

NSString *string = [[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding];
NSLog(@"the xml string is %@", string);

如果解析目标足够简单 - 就像找到一个标记的值一样 - 您可以使用字符串方法进行解析。否则,NSXMLParser或several other options可用。

要查看字符串是否包含子字符串,您可以执行以下操作:

if (string) {
    NSRange range = [string rangeOfString:@"<session-id>"];
    if (range.location != NSNotFound) {
        // session-id tag is at index range.location, so we know it's there
    }
}