使用NSXMLParser将字符串和图像添加到NSDictionary

时间:2010-10-22 13:24:04

标签: nsmutablearray nsxmlparser nsmutabledictionary

我正在使用NSXMLParser来解析包含视频信息的小型XML文件。 XML中的一个元素是指向与每个视频相关联的缩略图图像的URL。我正在尝试解析XML,获取ImageURL,然后使用它来获取图像并将其与视频名称等字符串一起存储。

我似乎无法让它发挥作用。我可以从调试器中看到字典具有图像的键/值对,并且图像是从URL创建的,但是我没有将它添加到NSDictionary中。 有什么建议?以下是处理解析的代码片段。

- (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:@"clipid"]) {
  // clear out our story item caches...
  item = [[NSMutableDictionary alloc] init];
  currentClipID = [[NSMutableString alloc] init];
  currentClipName = [[NSMutableString alloc] init];
  currentImageURL = [[NSMutableString alloc] init];
  currentImage = [[UIImage alloc] init];
 }
}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
 NSLog(@"found characters: %@", string);
 // save the characters for the current item...
 if ([currentElement isEqualToString:@"clipid"]) {
  [currentClipID appendString:string];
 } else if ([currentElement isEqualToString:@"clipname"]) {
  [currentClipName appendString:string];
 } else if ([currentElement isEqualToString:@"imageurl"]) {
  [currentImageURL appendString:string];
  //Take the Image URL, and convert it to an Image
  NSURL *imageURL = [NSURL URLWithString:string];
  NSData *data = [NSData dataWithContentsOfURL:imageURL];
  UIImage *image = [[UIImage alloc] initWithData:data];
  currentImage = //If it were a string I'd use appendString. How do I add this image to the Dictionary?
 }
}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{     
 NSLog(@"ended element: %@", elementName);
 if ([elementName isEqualToString:@"clipid"]) {
  // save values to an item, then store that item into the array...
  [item setObject:currentClipID forKey:@"clipid"];
  [item setObject:currentClipName forKey:@"clipname"];
  [item setObject:currentImageURL forKey:@"imageurl"];
  [item setObject:currentImage forKey:@"image"];
  //videos is an NSMutableArray
  [videos addObject:[item copy]];
 }

}

1 个答案:

答案 0 :(得分:4)

您需要将UIImage对象转换为可以存储在NSDictionary中的数据。

尝试:

NSData *imageData = UIImagePNGRepresentation(image);

然后,将imageData添加到字典中。

此外,只需将您的URL中的数据添加到NSDictionary。

相关问题