2013-03-20 74 views
3

我正在构建一个RSS阅读器应用程序,下面是教程,不包括哪些内容。从JSON中将图像存储到自定义类中iOS

到目前为止,我已经构建了一个名为blogPost的自定义类,它存储帖子名称和帖子作者,并使用基于名称的指定初始值设定项。

我试图在我的for循环中拉出帖子的缩略图,并将其显示在当前显示标题和作者属性的单元格中。

我成功地从JSON中拉出图像URL并对其进行解析,但似乎无法将图像存储在UIImage中。

//Custom header for BlogPost 

@interface BlogPost : NSObject 
@property (nonatomic, strong) NSString *title; 
@property (nonatomic, strong) NSString *author; 
@property (nonatomic, strong) UIImage *image; 

// Designated Initializer 
- (id) initWithTitle:(NSString *)title; 

+ (id) blogPostWithTitle:(NSString *)tile; 
@end 

而这里的tableViewController

[super viewDidLoad]; 

NSURL *blogUrl = [NSURL URLWithString:@"http://www.wheninmanila.com/api/get_recent_summary/"]; 
NSData *jsonData = [NSData dataWithContentsOfURL:blogUrl]; 
NSError *error = nil; 

NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error]; 

self.blogPosts = [NSMutableArray array]; 

NSArray *blogPostsArray = [dataDictionary objectForKey:@"posts"]; 

for (NSDictionary *bpDictionary in blogPostsArray) { 
    BlogPost *blogPost = [BlogPost blogPostWithTitle:[bpDictionary objectForKey:@"title"]]; 
    blogPost.author = [bpDictionary objectForKey:@"author"]; 

    NSURL *thumbURL = [bpDictionary objectForKey:@"thumbnail"]; 
    NSData *thumbData = [NSData dataWithContentsOfURL:thumbURL]; 

    blogPost.image = [[UIImage alloc] initWithData:thumbData]; 


    [self.blogPosts addObject:blogPost]; 
} 
+0

应用崩溃时,我尝试运行。踢出错误[__NSCFString isFileURL]:无法识别的选择器发送到实例 – 2013-03-20 08:30:10

回答

4

改变这一行:

NSURL *thumbURL = [bpDictionary objectForKey:@"thumbnail"]; 

要这样:

NSURL *thumbURL = [NSURL urlWithString:[bpDictionary objectForKey:@"thumbnail"]]; 

在你的字典中的值将是NSStrings,这与NSURL不一样。

+0

Bingo。谢谢!! – 2013-03-22 03:40:36

3

您正在使用NSURL代替NSStringNSString不响应到选择isFileURL(这就是为什么你得到的除外)。我假设你的缩略图是一个字符串,所以你应该得到它为NSString,比其转换为NSURL如下:

NSString *thumbAsString = [bpDictionary objectForKey:@"thumbnail"]; 
NSURL *thumbURL = [NSURL URLWithString:thumbAsString];