如何将 iOS / XCode 的 RSS 获取到 NSDictionary

How to get RSS for iOS / XCode into NSDictionary

我的以下代码在 iOS 中运行良好,但 XML- 文件的结构已更改,我不知道如何维护我的代码:-( 有人可以帮忙吗?如果可能的话,我只想更改此代码,因为其余代码应该可以正常工作。我看到下载本身工作正常,因为 receivedData 包含 53k,但我现在不知道如何将其传输到 NSDictionary 中......我已经阅读其他一些示例,但它们似乎使用了完全不同的代码,我不想重写应用程序的太多部分

- (NSDictionary *)getRSS: (NSString *)aKey
{
#define kURL @"https://developer.apple.com/news/rss/news.rss"
NSMutableString *finalURLStr = [NSMutableString stringWithString: kURL];
NSMutableURLRequest *request = nil;
NSHTTPURLResponse *response = nil;
NSError *error = nil;
NSData *receivedData = nil;
request = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: finalURLStr]
                                  cachePolicy: NSURLRequestUseProtocolCachePolicy
                              timeoutInterval: 60.0];
receivedData = [NSURLConnection sendSynchronousRequest: request
                                     returningResponse: &response
                                                 error: &error];
if (receivedData) {
    id jsonObj = [NSJSONSerialization JSONObjectWithData: receivedData
                                                 options: NSJSONReadingMutableContainers | NSJSONReadingAllowFragments
                                                   error: &error];
    NSArray *resultArray = (jsonObj != [NSNull null] ? [jsonObj objectForKey: @"data"] : nil);
    // Extract record from response
    if ([resultArray count])
        return [resultArray objectAtIndex: 0];
} else {
    // Handle the error
}
return nil;
}

非常感谢!!

link https://developer.apple.com/news/rss/news.rss 返回的是 RSS ,这实际上是 XML 格式的规范。

Apple 似乎只以 rss 格式提供此特定提要,而不是以 json 格式提供,因此要在您的应用中将此 link 转换为 NSDictionary,最简单的解决方案是使用某种 rss 解析器。例如。 https://github.com/Bitnock/BNRSSFeedParser

/克努特

正如其他人所说,返回的提要采用 XML 格式

如果您不想使用第 3 方库,而是想使用内置 API 将其解析为 JSON,您可以使用 XML -> JSON中间人 Web 服务。

Google 有其中之一,速度足够快,不会减慢您的反应速度。

https://ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=<NUMBER OF ENTRIES>&q=<XML URL HERE>

你的情况是:

https://ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=25&q=https://developer.apple.com/news/rss/news.rss

然后你可以通过responseData -> feed -> entries键将它解析为JSON,像这样:

NSDictionary *jsonObj = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSArray *entries = jsonObj[@"responseData"][@"feed"][@"entries"];
NSLog(@"%@", entries);  // 25 rss entries

link https://developer.apple.com/news/rss/news.rss return XML 数据所以你需要解析它才能使用。将 XML 字符串解析为任何类型的格式数据的最常见方法是使用 NSXMLParser.

我确实为你的情况编写了解析 XML 字符串的代码:

#import "AppDelegate.h"

@interface AppDelegate () <NSXMLParserDelegate>

@property (strong) NSMutableString *mutableData;

@property NSMutableDictionary *item; // temp item

@property NSMutableArray *items; // items

@property NSInteger channelFlag; // flag == 1 isChannel, flag == 0 isItem;

@property NSMutableDictionary *channel;

@end

@implementation AppDelegate

#define IsChannel 1
#define IsItem 0

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
#define kURL @"https://developer.apple.com/news/rss/news.rss"
    NSMutableString *finalURLStr = [NSMutableString stringWithString: kURL];
    NSMutableURLRequest *request = nil;
    NSHTTPURLResponse *response = nil;
    NSError *error = nil;
    NSData *receivedData = nil;
    request = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: finalURLStr]
                                      cachePolicy: NSURLRequestUseProtocolCachePolicy
                                  timeoutInterval: 60.0];
    receivedData = [NSURLConnection sendSynchronousRequest: request
                                         returningResponse: &response
                                                     error: &error];
    NSXMLParser *parser = [[NSXMLParser alloc] initWithData:receivedData];

    parser.delegate = self;
    self.channelFlag = -1;
    self.mutableData = [NSMutableString new];
    if (![parser parse]) {
        // Handle Parse XML Failed
    }
    NSLog(@"channel = %@", self.channel);
    return YES;
}

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict {
    //reset buffer memory
    [self.mutableData setString:@""];
    if ([elementName isEqualToString:@"channel"]) {
        self.channel = [NSMutableDictionary new];
        self.channelFlag = IsChannel;
    }
    if ([elementName isEqualToString:@"item"]) {
        self.item = [NSMutableDictionary new];
        if (!self.items) {
            self.items = [NSMutableArray new];
        }
        self.channelFlag = IsItem;
    }

    if ([elementName isEqualToString:@"atom:link"]) {
        self.channel[@"atomLink"] = attributeDict;
    }
}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
    // elementName exist in channel and item
    if ([elementName isEqualToString:@"title"]) {
        if (self.channelFlag == IsChannel) {
            self.channel[@"title"] = [self.mutableData copy];
        }
        if (self.channelFlag == IsItem) {
            self.item[@"title"] = [self.mutableData copy];
        }
    }
    if ([elementName isEqualToString:@"link"]) {
        if (self.channelFlag == IsChannel) {
            self.channel[@"link"] = [self.mutableData copy];
        }
        if (self.channelFlag == IsItem) {
            self.item[@"link"] = [self.mutableData copy];
        }
    }
    if ([elementName isEqualToString:@"description"]) {
        if (self.channelFlag == IsChannel) {
            self.channel[@"description"] = [self.mutableData copy];
        }
        if (self.channelFlag == IsItem) {
            self.item[@"description"] = [self.mutableData copy];
        }
    }
    // elementName only exist in channel
    if ([elementName isEqualToString:@"language"]) {
            self.channel[@"language"] = [self.mutableData copy];
    }
    if ([elementName isEqualToString:@"lastBuildDate"]) {
        self.channel[@"lastBuildDate"] = [self.mutableData copy];
    }
    if ([elementName isEqualToString:@"generator"]) {
        self.channel[@"generator"] = [self.mutableData copy];
    }
    if ([elementName isEqualToString:@"copyright"]) {
        self.channel[@"copyright"] = [self.mutableData copy];
    }
    // elementName only exist in item
    if ([elementName isEqualToString:@"pubDate"]) {
        self.item[@"pubDate"] = [self.mutableData copy];
    }
    if ([elementName isEqualToString:@"guid"]) {
        self.item[@"guid"] = [self.mutableData copy];
    }
    if ([elementName isEqualToString:@"content:encoded"]) {
        self.item[@"contentEncoded"] = [self.mutableData copy];
    }

    // add item to items
    if ([elementName isEqualToString:@"item"]) {
        [self.items addObject:self.item];
    }
    if ([elementName isEqualToString:@"channel"]) {
        self.channel[@"items"] = self.items;
    }
}

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

@end