ios - 图像 URL JSON 在应用程序错误中解析为 UIImageView

标签 ios json parsing

我正在尝试在 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/

相关文章:

Json 模式检查所有项目枚举是否存在于对象数组中

java - 时间戳转换问题

java - 使用 JsonPath 解析带有链接 hashmap java 的 Json

ios - 如何在 iOS 中将底部安全区域设置为 XIB?

ios - 周围没有任何东西的纹理

IOS Apple 通用链接随机失败

javascript - 如何使用 JavaScript 或 jQuery 清除 JSON 对象

javascript - 使用 angularjs 和 JSON 从数据库获取数据

parsing - 如何从 Scala 中的文件中获取第一行

ios - 如何在 Web 的轮播 View 中显示图像?