使用iPhone sdk从URL加载图像在图像视图中? [英] Loading image in image view from a URL, using the iPhone sdk?
问题描述
我尝试通过网址加载图片视图,从网上浏览了大量代码。不幸的是,我尝试的解决方案都没有为我工作,我得到了非常奇怪的错误。我正在获取图像数据,但没有来自此NSData的图像。我使用下面的代码和一个示例URL,它可以工作,给我代表的图像。但是,当我将其切换为使用我的实际URL时,我遇到了问题,因为它似乎试图创建/返回一个太大的图像。这是我的代码:
I've gone through a lot of code from the web in an attempt to load an image view via URL. Unfortunately, none of the solutions I tried has worked for me and I get very strange errors. I am getting image data, but no image from this NSData. I used the below code with a sample URL and it works, giving me the represented image. However when I switch it to use my actual URL I run into problems because it seems like it is attempting to create/return an image which is too large in size. Here is my code:
NSString *urlString = [[[_xmlDictionary objectForKey:@"response"] objectForKey:@"movie"] objectForKey:@"poster"];
NSArray *parts = [urlString componentsSeparatedByString:@"\""];
urlString = [parts objectAtIndex:1];
urlString = [urlString stringByAppendingFormat:@"/"];
urlString = [urlString
stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//NSURL * imageURL = [NSURL URLWithString:urlString];
NSLog(@"URL:%@",urlString);
NSURL * imageURL = [NSURL URLWithString:urlString];
NSData * imageData = [[NSData alloc] initWithContentsOfURL:imageURL];
UIImage * image = [[UIImage alloc] initWithData:imageData];
m_imageView = [[UIImageView alloc] initWithImage:image];
m_imageView.frame = CGRectMake(10, 10,300,300);
[self.view addSubview:m_imageView];
[imageData release];
[image release];
我很感激任何帮助,提前谢谢。
I'd appreciate any help, thanks in advance.
推荐答案
你可以转换哟你的URL到NSData的响应,然后使用
You can convert your response from your URL to NSData and then use
NSURL *url = [NSURL URLWithString:@"<YOUR URL STRING HERE>"];
NSData *data = [[NSData alloc] initWithContentsOfURL:url];
UIImage *tmpImage = [[UIImage alloc] initWithData:data];
yourImageView.image = tmpImage;
希望这会有所帮助。
编辑:
另外为了使它在后台工作,你应该以异步方式使用一个单独的线程调用它,这样它就不会阻塞你的主线程如下所示。
Also to make it work in background you should call it using a seperate thread in an asynchronous manner so that it wont block your main thread as shown below.
[NSThread detachNewThreadSelector:@selector(downloadAndLoadImage) toTarget:self withObject:nil];
这篇关于使用iPhone sdk从URL加载图像在图像视图中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!