ios - 将图像从 JSON 存储到自定义类 iOS

标签 ios json uiimage

我正在构建一个 RSS 阅读器应用程序,遵循教程等等。

到目前为止,我已经构建了一个名为 blogPost 的自定义类,它存储帖子名称和帖子作者,以及基于名称的指定初始化程序。

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

我成功地提取了图像 URL 并从 JSON 中解析了它,但似乎无法将图像存储在 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];
}

最佳答案

改变这一行:

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

对此:

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

字典中的值将是 NSStrings,这与 NSURL 的不同。

关于ios - 将图像从 JSON 存储到自定义类 iOS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15518541/

相关文章:

ios - UITableView - 如何在 + 和 - 单击时更新数组?

ios - 当应用程序在后台时,不会调用 AFHTTPSessionManager block

json - 使用 _contains 过滤大于、小于和范围的 JSON 字段 django

arrays - 如何将 perl 哈希数组编码为未命名的 JSON 数组?

ios - Change NSData Size of a UIImage - Compress And Resize UIImage With a Maximum Megabyte Mb 限制

ios - 图像显示不清晰

iphone - 每次在 xcode 中构建 "dependent Project"

ios - -systemLayoutSizeFittingSize : returning incorrect height for tableHeaderView under iOS 8

javascript - 从 JSON 对象中删除空格,但不在引号内

ios - OpenCV 代码导致 UIImages 泄漏