图像 URL JSON 解析为 UIImageView 在应用中出错



我正在尝试通过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 文件中的项目,标题和关于文本已成功解析为标签和文本视图。但图像不会解析。当我尝试对图像执行此操作时,该应用程序不断崩溃。

有人可以解释一下我做错了什么吗?

谢谢!

正如

@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];
    });
}

最新更新