如何在NSXMLParser中将不同URL中的解析数据保存到不同的数组?

时间:2013-12-02 09:16:09

标签: ios objective-c arrays nsxmlparser

我搜索了很多类似的问题,但无法弄清楚我的问题。

我有一个应用程序,其中嵌入了RSS源文件。我所做的是在我的根视图控制器中,我加载该本地文件并解析它,并在table view中显示数据。我还将每个项目的GUID保存在一个数组中。

我希望从服务器获取RSS提要链接并解析它,如果用户具有Internet访问权限,然后将该文件中的GUID项保存到另一个数组,并比较两者数组,然后将新项添加到表视图中的当前列表。

我的NIKFeedEntry作为解析数据的NSObject模型,NSXMLParser。我用两个URL的两个不同的解析器对象实例化它,但它们都被写在同一个对象中。因此,第一组解析数据显示的时间非常短,然后表视图使用新解析的数据重新加载数据,我不知道如何解决这个问题,以便解析第二个URL后,它会比较两个GUID的数组,如果有任何新项,则将这些项(XML数据)附加到我的本地XML文件,并显示旧数据和新数据的这种组合。

这是我的NIKFeedEntry.m

#import "NIKFeedEntry.h"

@implementation NIKFeedEntry

@synthesize lastBuildDate;
@synthesize radioTitle;
@synthesize podcastTitle;
@synthesize podcastDate;
@synthesize podcastURL;

@synthesize podcastAuthor;
@synthesize podcastContent;
@synthesize podcastGUID;
@synthesize podcastDownloadURL;
@synthesize podcastLinkURL;
@synthesize podcastSummary;
@synthesize categories;

- (id)initWithRadioTitle:(NSString*)radioTitle lastBuildDate:(NSDate*)lastBuildDate podcastTitle:(NSString*)podcastTitle podcastFile:(NSString*)podcastFile podcastDate:(NSDate*)podcastDate podcastDownloadURL:(NSString*)podcastDownloadURL
{
    return self;
}

@end

我的NIKFeedParser.m

//  NIKFeedParser.m

#import "NIKFeedParser.h"
#import "NIKMasterViewController.h"

@class NIKMasterViewController;

NIKMasterViewController *masterVC;


@interface NIKFeedParser (Private)

- (NSString *)trimString:(NSString *)originalString;

@end

@implementation NIKFeedParser

@synthesize currentItem;
@synthesize currentItemValue;
@synthesize feedItems;
@synthesize delegate;
@synthesize retrieverQueue;
@synthesize parsingFeedsWithNumbers;
@synthesize queue;
@synthesize selectedCategory;
@synthesize feedURL;
@synthesize downloadURL;
@synthesize lastModified;
@synthesize RSSURL;
@synthesize updatedGUIDs;

- (id)initWithRSSURL:(NSURL *)rssURL{
    self = [super init];
    if (self) {
        feedItems = [[NSMutableArray alloc]init];
        RSSURL = rssURL;
    }
    return self;
}


- (NSOperationQueue *)retrieverQueue
{
    if (nil == retrieverQueue)
    {
        retrieverQueue = [[NSOperationQueue alloc] init];
        retrieverQueue.maxConcurrentOperationCount = 1;
    }

    return retrieverQueue;
}

- (void) startDownloading
{
//  ?? [feedItems removeAllObjects];
    NSString *file = [[NSBundle  mainBundle] pathForResource:@"Feed"
                                                      ofType:@"plist"];
    NSDictionary *item = [[NSDictionary alloc]initWithContentsOfFile:file];
    NSArray *array = [item objectForKey:@"Root"];
    NSString *theURL = [[array objectAtIndex:selectedCategory.intValue] objectForKey:@"URL"];
    NSLog(@"url:%@",theURL);
    NSURL * url = [NSURL URLWithString:theURL];
    NSURLRequest * urlRequest = [NSURLRequest requestWithURL:url];

    NSURLConnection * download = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self];
    [download start];
}

#pragma mark -
#pragma mark Private Methods


- (NSString *)trimString:(NSString *)originalString
{
    NSString * trimmedString;
    trimmedString  = [originalString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    return trimmedString;
}

#pragma mark -
#pragma mark NSURLConnectionDelegate

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    //This method is called when the download begins.
    //You can get all the response headers

    /* create the NSMutableData instance that will hold the received data */

    long long contentLength = [response expectedContentLength];
    if (contentLength == NSURLResponseUnknownLength) {
        contentLength = 500000;
    }


    if (downloadedData!=nil)
    {
        downloadedData = nil;
    }
    downloadedData = [NSMutableData dataWithCapacity:(NSUInteger)contentLength];

}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    //This method is called whenever there is downloaded data available
    //It will be called multiple times and each time you will get part of downloaded data
    [downloadedData appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    //This method is called once the download is complete


    //The next step is parse the downloaded xml feed
    [feedItems removeAllObjects];
    NSXMLParser * xmlParser = [[NSXMLParser alloc] initWithData:downloadedData];
    [self startParsingWithParser:xmlParser];

    updatedGUIDs = [[NSMutableArray alloc] init];

    for (int i = 0; i < feedItems.count; i++) {
        [updatedGUIDs insertObject: [[feedItems objectAtIndex:i]podcastGUID]  atIndex:i];
    }

}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{

    [error localizedDescription];
    NSLog(@"%@", [error localizedDescription]);
    [self.delegate parserHasError:error];

}

#pragma mark -
#pragma mark NSXMLParserDelegate
- (void) startParsingWithParser: (NSXMLParser *)parser
{

    [parser setDelegate:self];
    [parser setShouldProcessNamespaces:YES];
    [parser setShouldReportNamespacePrefixes:YES];
    [parser setShouldResolveExternalEntities:NO];
    [parser parse];
}

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict
{
    if(nil != qualifiedName)
    {
        elementName = qualifiedName;
    }
    parseElement = NO;
    if ([elementName isEqualToString:@"lastBuildDate"])
    {
        lbd = [[NSString alloc] init];
    }

    if ([elementName isEqualToString:@"item"])
    {
        currentItem = [[NIKFeedEntry alloc] init];
    } else if([elementName isEqualToString:@"title"] ||
              [elementName isEqualToString:@"guid"] ||
              [elementName isEqualToString:@"description"] ||
              [elementName isEqualToString:@"content:encoded"] ||
              [elementName isEqualToString:@"link"] ||
              [elementName isEqualToString:@"category"] ||
              [elementName isEqualToString:@"dc:creator"] ||
              [elementName isEqualToString:@"pubDate"] ||
              [elementName isEqualToString:@"enclosure"] ||
              [elementName isEqualToString:@"lastBuildDate"])
    {
        NSString *urlValue=[attributeDict valueForKey:@"url"];
        NSString *urlType=[attributeDict valueForKey:@"type"];
        parseElement = YES;
        if ([urlType  isEqualToString:@"audio/ogg"] && ([urlValue rangeOfString:@"jadi.net"].length != 0))
        {
            downloadURL = [urlValue stringByReplacingOccurrencesOfString:@"jadi.net" withString:@"192.168.2.1"];
            downloadURL = [downloadURL stringByReplacingOccurrencesOfString:@"ogg" withString:@"mp3"];
            [currentItem setPodcastDownloadURL:downloadURL];
        }
    }

}


- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
    if(nil != qName)
    {
        elementName = qName;
    }

    NSString * parsedElementContent = nil;

    if (parsedElementData != nil) {
        parsedElementContent = [[NSString alloc] initWithData:parsedElementData encoding:NSUTF8StringEncoding];
    } else if (parsedElementString != nil) {
        parsedElementContent = [[NSString alloc] initWithString:parsedElementString];
    }
    if ([elementName isEqualToString:@"lastBuildDate"]) {
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"EEE, d MMM yyyy HH:mm:ss Z"];
        NSDate *lastSavedBuildDate = [formatter dateFromString:[self trimString:parsedElementContent]];
        [[NSUserDefaults standardUserDefaults] setObject:lastSavedBuildDate forKey:@"Date"];

    }
    if([elementName isEqualToString:@"title"])
    {
        [currentItem setPodcastTitle:[self trimString:parsedElementContent]];
    }
    else if([elementName isEqualToString:@"guid"])
    {
        [currentItem setPodcastGUID:[self trimString:parsedElementContent]];
    }
    else if([elementName isEqualToString:@"description"])
    {
        [currentItem setPodcastSummary:[self trimString:parsedElementContent]];
    }
    else if([elementName isEqualToString:@"content:encoded"])
    {
        [currentItem setPodcastContent:[self trimString:parsedElementContent]];
    }
    else if([elementName isEqualToString:@"link"])
    {
        [currentItem setPodcastLinkURL:[self trimString:parsedElementContent]];
    }
    else if([elementName isEqualToString:@"category"])
    {
        [currentItem addPodcastCategory:[self trimString:parsedElementContent]];
    }
    else if([elementName isEqualToString:@"dc:creator"])
    {
        [currentItem setPodcastAuthor:[self trimString:parsedElementContent]];
    }
    else if([elementName isEqualToString:@"pubDate"])
    {
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"EEE, d MMM yyyy HH:mm:ss Z"];
        [currentItem setPodcastDate:[formatter dateFromString:[self trimString:parsedElementContent]]];
    }
    else if([elementName isEqualToString:@"item"])
    {
        [feedItems addObject:currentItem];
        currentItem = nil;
    }

    if (parsedElementContent!=nil)
    {
        parsedElementContent = nil;
    }

    if (parsedElementString!=nil)
    {
        parsedElementString = nil;
    }

    if (parsedElementData!=nil)
    {
        parsedElementData = nil;
    }

}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
    if (!parseElement)
    {
        return;
    }
    if (parsedElementString==nil)
    {
        parsedElementString = [[NSMutableString alloc] init];
    }
    [parsedElementString appendString:string];
}

- (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError
{
    NSLog(@"parseErrorOccured: %@",[parseError localizedDescription]);

}

- (void)parserDidEndDocument:(NSXMLParser *)parser
{
    if (downloadedData!=nil)
    {
        downloadedData = nil;
    }
    [self.delegate parserDidCompleteParsing];
}

@end

2 个答案:

答案 0 :(得分:2)

在下载后,请使用 GDataXMLNode Hear i attach its .h and .m而不是使用此过程,请使用步骤: -

  • 下载并解压缩zip并将此两个课程添加到您的项目GDataXMLNode.hGDataXMLNode.m

  • #import "GDataXMLNode.h"在您的班级中,您要调用您的xmp网址。

  • 将此Bellow方法用于分析数据: -


-(void)ActionCountAlikes
{
NSString *urlParsingStr =@"http://youryoue.php"



    NSData *xmlData = [[NSMutableData alloc] initWithContentsOfURL:[NSURL URLWithString:urlParsingStr]];

    NSError *error;
    GDataXMLDocument *xmlDocument = [[GDataXMLDocument alloc] initWithData:xmlData
                                                                   options:0 error:&error];
    NSArray *getData = [[xmlDocument rootElement]elementsForName:@"Record"];

        for(GDataXMLElement *e in getData)
        {
             NSMutableDictionary *d = [[NSMutableDictionary alloc] init];
            [d setValue:[[[e elementsForName:@"Message"]objectAtIndex:0]stringValue] forKey:@"Message"];


        }


    }

答案 1 :(得分:1)

NSXMLParserDelegate的所有方法都会返回对来电者parser:(NSXMLParser *)parser的引用。您可以将它用于单独的数据。在属性中保留对解析器实例的引用,并使用它们进行比较。