从XML url获取图像并加载到UITableView中

时间:2011-04-30 09:52:19

标签: iphone xml uitableview

我遇到了这个问题,我会尝试解决它。 在方法中:

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

我写道:

NSMutableString *urlXML = [NSMutableString stringWithFormat:@"%@", [[elencoFeed objectAtIndex:indexPath.row]objectForKey:@"img"]];
NSMutableData *imageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:urlXML]];
NSLog(@"imgdata: %@",imageData);

xml写成:

<img>http://site/blu.png</img>

但问题是“urlXML”它会响应XML标记内的URL 但是“imageData”,它以“(null)”响应日志。

我要做的就是在UITableView中放入每行的图像。 我哪里错了?

1 个答案:

答案 0 :(得分:0)

尝试修剪并转义你的urlXML字符串,如下所示:

// Assuming this returns a string with a valid URL (taken from question)
NSString *urlXML = [NSMutableString stringWithFormat:@"%@", [[elencoFeed objectAtIndex:indexPath.row]objectForKey:@"img"]];
// reading @Filippo's comments looks like the string returned contains trailing tabs and line breaks, let's trim it
NSString *trimmed = [urlXML stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSURL *url = [NSURL URLWithString:[trimmed stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSError *error = nil;
NSData *imageData = [[NSData alloc] initWithContentsOfURL:url options:0 error:&error];
if (error) {
    NSLog(@"error %@, %@", error, [error userInfo]);
}