我正在尝试在 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];
});
我已将 socket 连接到 .xib 文件中的项目,并且标题和关于文本已成功解析为标签和 TextView 。但图像不会解析。当我尝试对图像执行此操作时,应用程序不断崩溃。
有人可以解释一下我做错了什么吗?
谢谢!
最佳答案
正如 @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];
});
}
关于ios - 图像 URL JSON 在应用程序错误中解析为 UIImageView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19144747/