xml解析图像不能在uitableviewcell中工作

时间:2012-07-18 00:43:43

标签: iphone xcode uitableview rss nsxmlparser

我已成功解析了该名称,但它显示在cell.textLabel.text中,但另一方面图像未显示。当我键入本地图像的名称作为字符串时,它工作,但当我将它连接到解析的图像字符串时,它不显示。想一想为什么会这样?感谢。

  - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *MyIdentifier = @"MyIdentifier";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:MyIdentifier] autorelease];
    }

    // Set up the cell
    int storyIndex = [indexPath indexAtPosition: [indexPath length] - 1];

    [cell setText:[[stories objectAtIndex: storyIndex] objectForKey: @"Name"]];
    cell.textLabel.font = [UIFont fontWithName:@"Arial" size:18];
    NSString * storyLink = [[stories objectAtIndex: storyIndex] objectForKey: @"Image"];

    NSURL *url = [NSURL URLWithString:storyLink];
    NSData *data = [NSData dataWithContentsOfURL:url];
    UIImage *background = [[UIImage alloc] initWithData:data];
    cell.imageView.image = background;
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // Navigation logic

  }


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];

    if ([stories count] == 0) {
        NSString * path = @"http://travisupload.weebly.com/uploads/9/0/0/1/9001440/sports.xml";
        [self parseXMLFileAtURL:path];
    }

    cellSize = CGSizeMake([newsTable bounds].size.width, 60);
}

- (void)viewWillDisappear:(BOOL)animated {
}

- (void)viewDidDisappear:(BOOL)animated {
}




- (void)parserDidStartDocument:(NSXMLParser *)parser{
    NSLog(@"found file and started parsing");

}

- (void)parseXMLFileAtURL:(NSString *)URL
{
    stories = [[NSMutableArray alloc] init];

    //you must then convert the path to a proper NSURL or it won't work
    NSURL *xmlURL = [NSURL URLWithString:URL];

    // here, for some reason you have to use NSClassFromString when trying to alloc NSXMLParser, otherwise you will get an object not found error
    // this may be necessary only for the toolchain
    rssParser = [[NSXMLParser alloc] initWithContentsOfURL:xmlURL];

    // Set self as the delegate of the parser so that it will receive the parser delegate methods callbacks.
    [rssParser setDelegate:self];

    // Depending on the XML document you're parsing, you may want to enable these features of NSXMLParser.
    [rssParser setShouldProcessNamespaces:NO];
    [rssParser setShouldReportNamespacePrefixes:NO];
    [rssParser setShouldResolveExternalEntities:NO];

    [rssParser parse];

}

- (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError {
    NSString * errorString = [NSString stringWithFormat:@"Unable to download story feed from web site (Error code %i )", [parseError code]];
    NSLog(@"error parsing XML: %@", errorString);

    UIAlertView * errorAlert = [[UIAlertView alloc] initWithTitle:@"Error loading content" message:errorString delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [errorAlert show];
}

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{
    //NSLog(@"found this element: %@", elementName);
    currentElement = [elementName copy];
    if ([elementName isEqualToString:@"Sport"]) {
        // clear out our story item caches...
        item = [[NSMutableDictionary alloc] init];
        currentName = [[NSMutableString alloc] init];
        currentDate = [[NSMutableString alloc] init];
        currentSummary = [[NSMutableString alloc] init];
        currentImage = [[NSMutableString alloc] init];
    }

}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{
    //NSLog(@"ended element: %@", elementName);
    if ([elementName isEqualToString:@"Sport"]) {
        // save values to an item, then store that item into the array...
        [item setObject:currentName forKey:@"Name"];
        [item setObject:currentImage forKey:@"Image"];
        [item setObject:currentSummary forKey:@"summary"];
        [item setObject:currentDate forKey:@"date"];


        [stories addObject:[item copy]];
        NSLog(@"adding story: %@", currentName);
    }

}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
    //NSLog(@"found characters: %@", string);
    // save the characters for the current item...
    if ([currentElement isEqualToString:@"Name"]) {
        [currentName appendString:string];
    } else if ([currentElement isEqualToString:@"Image"]) {
        [currentImage appendString:string];
    } else if ([currentElement isEqualToString:@"description"]) {
        [currentSummary appendString:string];
    } else if ([currentElement isEqualToString:@"pubDate"]) {
        [currentDate appendString:string];
    }


}

- (void)parserDidEndDocument:(NSXMLParser *)parser {

    [activityIndicator stopAnimating];
    [activityIndicator removeFromSuperview];

    NSLog(@"all done!");
    NSLog(@"stories array has %d items", [stories count]);
    [newsTable reloadData];
}





- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
    // Release anything that's not essential, such as cached data
}


- (void)dealloc {

    [currentElement release];
    [rssParser release];
    [stories release];
    [item release];
    [currentName release];
    [currentDate release];
    [currentSummary release];
    [currentImage release];

    [super dealloc];
}

2 个答案:

答案 0 :(得分:0)

请勿在主线程上下载图像。尝试使用具有UIImageView类别的缓存支持的SDWebImage异步图像下载器。

答案 1 :(得分:0)

试试这段代码!!

NSString *imageStr = [imageURLArray objectAtIndex:indexPath.row];
NSString *trimmedString = [imageStr stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSString *string1=[trimmedString stringByReplacingOccurrencesOfString:@"/n" withString:@""];
NSURL *url = [NSURL URLWithString:string1];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *newImage = [UIImage imageWithData:data];
cell.imageView.image = newImage;