在其他数据(特别是字符串)中,我从JSON中提取了一个URL,并将其保存在数组“jsonArray”中。我需要将该URL(用于与登录用户有关的图像)转换为可以在我的imageview“imageProfPic”中显示的实际图像。我对GCD不太熟悉,因此,我非常感谢我的代码提供的所有帮助以及如何将我的图像成功显示在imageProfPic中。
(编辑:忘记了,我收到错误“_NSCFString isFileURL”)
TableViewController.m文件 NSURL *myURL = [[NSURL alloc]initWithString:@"http://domain.com/json2.php"];
NSData *myData = [[NSData alloc]initWithContentsOfURL:myURL];
NSError *error;
jsonArray = [NSJSONSerialization JSONObjectWithData:myData options:NSJSONReadingMutableContainers error:&error];
[tableView reloadData]; // if tableView is unidentified make the tableView IBOutlet
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return jsonArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NeedCardTableViewCell *cell = (NeedCardTableViewCell *) [tableView dequeueReusableCellWithIdentifier:@"needCard" forIndexPath:indexPath];
NSDictionary *needs = jsonArray[indexPath.row]; // get the data dict for the row
cell.textNeedTitle.text = [needs objectForKey: @"needTitle"];
cell.textNeedPoster.text = [needs objectForKey: @"needPoster"];
cell.textNeedDescrip.text = [needs objectForKey: @"needDescrip"];
dispatch_async(dispatch_queue_create("imageQueue", NULL), ^{
UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:needs[@"userImage"]]];
dispatch_async(dispatch_get_main_queue(), ^{
[cell.imageProfPic setImage:image];
});
});
return cell;
TableViewController.h文件@interface NeedCardTableViewCell : UITableViewCell
@property (weak, nonatomic) IBOutlet UILabel *textNeedTitle;
@property (weak, nonatomic) IBOutlet UILabel *textNeedPoster;
@property (weak, nonatomic) IBOutlet UILabel *textNeedDescrip;
@property (weak, nonatomic) IBOutlet UIImageView *imageProfPic;
@property (strong, nonatomic) IBOutlet UITableView *tableView;
最佳答案
我认为您只需要使用字符串创建一个NSURL,就可以了。试试看:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
NSURL *imageURL = [NSURL URLWithString:needs[@"userImage"]];
UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:imageURL]];
dispatch_async(dispatch_get_main_queue(), ^{
[cell.imageProfPic setImage:image];
});
});
关于ios - 使用Grand Central Dispatch将URL字符串从JSON转换为ImageView的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23073089/