从 RSS Feed 创建 NSDictionary?

发布于 2024-10-19 07:17:41 字数 127 浏览 3 评论 0原文

我用谷歌搜索了一下,但找不到关于这个主题的全部内容。我有 RSS 提要的 URL,并且想知道如何以 NSDictionary 的形式将该内容获取到我的应用程序中。我可以使用 NSData 的 initWithContentsOfURL 吗?

I Googled around a bit, but can't find a whole lot on the subject. I have the URL to an RSS feed, and I want to know how to go about getting that content into my app in the form of an NSDictionary. Could I use NSData's initWithContentsOfURL?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

橘虞初梦 2024-10-26 07:17:41

您需要做两件事:

  1. 检索 XML 中的 RSS 内容
  2. 解析检索到的 XML 文件

检索 RSS 提要数据

Apple 文档包含许多使用 NSURLConnection 从 Web 服务检索数据的示例。 Apple 文档中提供了很多示例。以下是要点。

首先,您需要使用正确的 URL 初始化连接并启动它。下面的代码显示了如何执行此操作:

// Create a URL for your rss feed
NSURL *url = [NSURL URLWithString:@"http://yourrssfeedurl"];    
// Create a request object with that URL
NSURLRequest *request = [NSURLRequest requestWithURL:url 
                                         cachePolicy:NSURLRequestReloadIgnoringCacheData
                                     timeoutInterval:30];

// Clear the existing connection if there is one
if (connectionInProgress) {
    [connectionInProgress cancel];
    [connectionInProgress release];
}

// Instantiate the object to hold all incoming data
[receivedData release];
receivedData = [[NSMutableData alloc] init];

// Create and initiate the connection - non-blocking
connectionInProgress = [[NSURLConnection alloc] initWithRequest:request 
                                                       delegate:self 
                                               startImmediately:YES];

在此代码中,connectionInProgress 是在执行连接的类中定义的 NSURLConnection 类型的 ivar。

然后,您需要实现 NSURLConnectionDelegate 方法:

// This method is called everytime the current connection receives data
-(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [receivedData appendData:data];
}

// This method is called once the connection is completed
-(void) connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSString *xmlCheck = [[[NSString    alloc] initWithData:receivedData
                                        encoding:NSUTF8StringEncoding] autorelease];
    NSLog(@"xmlCheck = %@", xmlCheck);

    // Release our memory: we're done!
    [connectionInProgress release];
    connectionInProgress = nil;

    [receivedData release];
    receivedData = nil; 
}

// This method is called when there is an error
-(void) connection:(NSURLConnection *)connection 
  didFailWithError:(NSError *)error
{
    [connectionInProgress release];
    connectionInProgress = nil;

    [receivedData release];
    receivedData = nil;

    NSString *errorString = [NSString stringWithFormat:@"Fetch failed: %@", [error localizedDescription]];

    NSLog(@"%@", errorString);
}

在上面的代码中,receivedData 是执行连接的类中定义的 NSMutableData 类型的 ivar。

解析 XML

使用 NSXMLParser 类解析刚刚检索到的 xml 文件非常简单。

调用解析器的类需要实现 NSXMParserDelegate 协议。在处理解析的对象(本例中为 DataManager)的 .h 中是这样完成的:

@interface DataManager : _DataManager <NSXMLParserDelegate>
{
}

在实现文件中,您至少需要实现以下方法:

每次在中找到新 XML 标记时调用的方法你的 xml 文件。通常,您可以在此处定义新对象,以便可以在读取它们时设置它们的属性,也可以在此处清除用于存储在 XML 文件中找到的字符的字符串。

- (void)parser:(NSXMLParser *)parser 
didStartElement:(NSString *)elementName 
  namespaceURI:(NSString *)namespaceURI 
 qualifiedName:(NSString *)qualifiedName 
    attributes:(NSDictionary *)attributeDict

每次解析器在文件中找到字符(而不是元素名称)时调用的方法。这里 currentElementString 是一个“NSMutabletring”类型的 ivar。

- (void)parser:(NSXMLParser *)parser 
foundCharacters:(NSString *)string
{
    [currentElementString appendString:string];
}

Last 每当元素读取完成时调用的方法。这通常是您将任何完全解析的元素存储到数据结构层次结构(字典或其他)中的地方:

- (void)parser:(NSXMLParser *)parser 
 didEndElement:(NSString *)elementName 
  namespaceURI:(NSString *)namespaceURI 
 qualifiedName:(NSString *)qName

当您告诉解析器这样做时,解析就会开始。这是一个同步调用,即它将阻止您的应用程序,直到解析结束。以下是定义解析器并调用它的方法:

// Create an XML parser with the data received from the web service
NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data];

// Give the parser  delegate
[parser setDelegate:self];

// Tell the parser to start parsing - The complete document will be parsed and the delegate to 
// of NSXMLParser will get all of its delegate messages sent to it before this line finishes
// execution. The parser is blocking.
[parser parse];

// Parser has finished its job, release it
[parser release];

最后一条建议。通常,在 didStartElement 和 didEndElement 方法中您将有一个很大的 if...else if 语句,您需要在其中将 elementName 与您期望的元素名称进行比较。建议使用可在两种方法中使用的常量字符串定义,而不是在方法中键入字符串。这意味着:

static NSString *ks_ElementName1 = @"ElementName1";

应该在 didStartElement 和 didEndElement 方法中声明和使用,以标识 XML 中的“ElementName1”。

瞧,祝您的应用程序好运。

You need two things:

  1. retrieving the content of your RSS in XML
  2. parsing the retrieved XML file

Retrieving the RSS feed data

The Apple documentation contains many examples of retrieving data from a web service using NSURLConnection. Lots of examples are available on the Apple documentation. Here are the main points though.

First you need to initialize your connection with a proper URL and initiate it. The code below shows how to do this:

// Create a URL for your rss feed
NSURL *url = [NSURL URLWithString:@"http://yourrssfeedurl"];    
// Create a request object with that URL
NSURLRequest *request = [NSURLRequest requestWithURL:url 
                                         cachePolicy:NSURLRequestReloadIgnoringCacheData
                                     timeoutInterval:30];

// Clear the existing connection if there is one
if (connectionInProgress) {
    [connectionInProgress cancel];
    [connectionInProgress release];
}

// Instantiate the object to hold all incoming data
[receivedData release];
receivedData = [[NSMutableData alloc] init];

// Create and initiate the connection - non-blocking
connectionInProgress = [[NSURLConnection alloc] initWithRequest:request 
                                                       delegate:self 
                                               startImmediately:YES];

In this code the connectionInProgress is an ivar of type NSURLConnection defined in the class performing the connection.

Then you need to implement the NSURLConnectionDelegate methods:

// This method is called everytime the current connection receives data
-(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [receivedData appendData:data];
}

// This method is called once the connection is completed
-(void) connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSString *xmlCheck = [[[NSString    alloc] initWithData:receivedData
                                        encoding:NSUTF8StringEncoding] autorelease];
    NSLog(@"xmlCheck = %@", xmlCheck);

    // Release our memory: we're done!
    [connectionInProgress release];
    connectionInProgress = nil;

    [receivedData release];
    receivedData = nil; 
}

// This method is called when there is an error
-(void) connection:(NSURLConnection *)connection 
  didFailWithError:(NSError *)error
{
    [connectionInProgress release];
    connectionInProgress = nil;

    [receivedData release];
    receivedData = nil;

    NSString *errorString = [NSString stringWithFormat:@"Fetch failed: %@", [error localizedDescription]];

    NSLog(@"%@", errorString);
}

In the code above receivedData is an ivar of type NSMutableData defined in the class performing the connection.

Parsing XML

Parsing the xml file you have just retrieved is quite straightforward using the NSXMLParser class.

The class calling the parser needs to implement the NSXMParserDelegate protocol. This is done like this in the .h of the object dealing with the parsing (DataManager in this example):

@interface DataManager : _DataManager <NSXMLParserDelegate>
{
}

And in the implementation file you need to implement at least the following methods:

The method called every time a new XML tag if found in your xml file. This is typically where you will either define new objects so you can set their properties as they are being read or where you will clear the string used to store the characters found in your XML file.

- (void)parser:(NSXMLParser *)parser 
didStartElement:(NSString *)elementName 
  namespaceURI:(NSString *)namespaceURI 
 qualifiedName:(NSString *)qualifiedName 
    attributes:(NSDictionary *)attributeDict

The method called every time the parser finds characters in your file (not elements names). Here currentElementString is an ivar of type 'NSMutabletring'.

- (void)parser:(NSXMLParser *)parser 
foundCharacters:(NSString *)string
{
    [currentElementString appendString:string];
}

Last the method called whenever reading of an element is completed. This is typically where you would store any completely parsed element into your data structure hierarchy (dictionary or otherwise):

- (void)parser:(NSXMLParser *)parser 
 didEndElement:(NSString *)elementName 
  namespaceURI:(NSString *)namespaceURI 
 qualifiedName:(NSString *)qName

The parsing starts when you tell the parser to do so. It's a synchronous call, i.e. it will block you application until the parsing is over. Here is how you define the parser and call it:

// Create an XML parser with the data received from the web service
NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data];

// Give the parser  delegate
[parser setDelegate:self];

// Tell the parser to start parsing - The complete document will be parsed and the delegate to 
// of NSXMLParser will get all of its delegate messages sent to it before this line finishes
// execution. The parser is blocking.
[parser parse];

// Parser has finished its job, release it
[parser release];

One last piece of advice. Typically you will have a big if...else if statement in the didStartElement and didEndElement methods where you need to compare the elementName to the names of the elements you expect. It is advisable to use constant string definitions which you can use in both methods as opposed to typing the strings in the methods. This means this:

static NSString *ks_ElementName1 = @"ElementName1";

should be declared and used in both didStartElement and didEndElement methods to identify "ElementName1" in your XML.

Voilà, good luck with your app.

书间行客 2024-10-26 07:17:41

关于使用 NSXMLParser -(void)initWithContentsOfURL:(NSURL *)url 而不是使用 NSURLConnection 加载数据的注意事项。 NSURLConnection 是非阻塞的,在它自己管理的单独线程中加载数据,在需要时调用定义的委托。相反,如果在主线程上调用,NSXMLParser initWithContentsOfURL 方法将阻塞。

One note about using NSXMLParser -(void)initWithContentsOfURL:(NSURL *)url instead of using NSURLConnection to load the data. NSURLConnection is non-blocking, loading the data in a separate thread managed by itself, calling the defined delegate when required. Conversely, the NSXMLParser initWithContentsOfURL method will block if called on the main thread.

等往事风中吹 2024-10-26 07:17:41

检查 NSXMLParser 类的文档。您可以 initWithContentsofURL,然后按照您认为合适的方式操作数据。

Check the documentation for the NSXMLParser Class. You can initWithContentsofURL and then manipulate the data how you see fit.

错々过的事 2024-10-26 07:17:41

我曾经开始过一个项目,其中涉及类似的事情,但由于不相关的原因而被放弃。您应该查看 NSXMLParser (文档链接) 来解析您的 XML feed。您可以轻松分解元素并将它们添加到您喜欢的任何数据结构中。

I once began a project which involved something like this which was abandoned for unrelated reasons. You should look into NSXMLParser (documentation link) to parse your XML feed. You can easily break up elements and add them into whatever data structure you like.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文