如何从URL显示图像并将其加载到UIImageView中

时间:2015-03-18 12:44:48

标签: ios xcode image uiimageview

我需要将URL中的图像加载到UIImageView中。每次URL都不同,因为我是JSON解析网站。我能够获取URL。但是,当我运行应用程序时,UIImageView中没有图像。

这是我的代码

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    if ([eventNameDesc containsString:@"src="]) {
        eventNameDesc = @"";
    }
    else {
        eventDescription.text = eventNameDesc;
    }
    self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAction target:self action:@selector(shareButtonPressed)];


}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(IBAction)shareButtonPressed {
    NSString *shareText = eventNameDesc;
    NSArray *itemsToShare = @[shareText];
    UIActivityViewController *activityVC = [[UIActivityViewController alloc] initWithActivityItems:itemsToShare applicationActivities:nil];
    activityVC.excludedActivityTypes = @[];
    [self presentViewController:activityVC animated:YES completion:nil];
}

- (void)loadImage {
    NSData* imageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:self.imageURL]];
    UIImage* image = [[UIImage alloc] initWithData:imageData];
    [self performSelectorOnMainThread:@selector(displayImage:) withObject:image waitUntilDone:NO];
}

- (void)displayImage:(UIImage *)image {
    [self.ImageView setImage:image]; //UIImageView
}

@end

我的代码出了什么问题?有人请帮忙。

1 个答案:

答案 0 :(得分:0)

您可以使用提供的代码here

制作UIImage个对象

之后,您可以将UIImage对象添加到任何UIImageView对象。 这是适合我的代码。

UIImage *anImage = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://4.bp.blogspot.com/-K7vl-ShXrNc/VQU-D0NTFgI/AAAAAAAAAOg/aBIUOwF2nEQ/s1600/contact.png"]]];
UIImageView *temp = [[UIImageView alloc] initWithImage:anImage];
[self.view addSubview:temp];

这是screenshot.