2013-03-20 67 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];