我正在尝试在我的iPhone应用程序中通过JSON解析图像URL。 我的json模型是这样构建的:
{
"picture":"link_to_image.jpg",
"about":"about text here",
"name":"Name"
}
我使用此代码解析我的应用中的itemw:
- (void)fetchedData:(NSData *)responseData
{
NSError *error;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:responseData
options:kNilOptions error:&error];
self.titleLabel.text = [json objectForKey:@"name"];
self.aboutText.text = [json objectForKey:@"about"];
self.profileImage.image = [json objectForKey:@"picture"];
}
在ViewDidLoad中我写了这个:
dispatch_queue_t queue = dispatch_get_global_queue
(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
NSData *data = [NSData dataWithContentsOfURL:
[NSURL URLWithString:@"link_to_my_json_file.php"]];
[self performSelectorOnMainThread:@selector(fetchedData:)
withObject:data waitUntilDone:YES];
});
我已将插座连接到.xib文件中的项目,标题和文本已成功解析为标签和textview。但图像不会解析。当我为图像尝试这个时,应用程序不断崩溃。
有人可以解释一下我做错了吗?
谢谢!
答案 0 :(得分:1)
正如@Hot Licks在评论中提到的那样,你将一个NSString指针放入UIImage属性中。以下方法应该有效。
- (void)fetchedData:(NSData *)responseData
{
NSError *error;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:responseData
options:kNilOptions error:&error];
self.titleLabel.text = [json objectForKey:@"name"];
self.aboutText.text = [json objectForKey:@"about"];
NSURL *URL = [NSURL URLWithString: [json objectForKey:@"picture"]];
dispatch_queue_t queue = dispatch_get_global_queue
(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
NSData *data = [NSData dataWithContentsOfURL: URL];
self.profileImage.image = [UIImage imageWithData: data];
});
}