Iphone 使用url设置UIImageView图像
可以读取图像的url并在此url处为图像设置UIImageView吗?可以从url加载NSData并将其转换为图像并将其粘贴到图像视图中,但这是一个非常糟糕的主意,因为它涉及在主线程上进行同步url下载。这将锁定用户界面,如果图像下载速度不够快,用户可能会认为你的应用程序已经崩溃 编辑:为了澄清问题,在我看来,原来的问题似乎是海报想说一些与Iphone 使用url设置UIImageView图像,iphone,uiimageview,Iphone,Uiimageview,可以读取图像的url并在此url处为图像设置UIImageView吗?可以从url加载NSData并将其转换为图像并将其粘贴到图像视图中,但这是一个非常糟糕的主意,因为它涉及在主线程上进行同步url下载。这将锁定用户界面,如果图像下载速度不够快,用户可能会认为你的应用程序已经崩溃 编辑:为了澄清问题,在我看来,原来的问题似乎是海报想说一些与 imageView.image = [UIImage imageWithContentsOfURL:theURL]; 这就是我的答案。通过浏览NSData
imageView.image = [UIImage imageWithContentsOfURL:theURL];
这就是我的答案。通过浏览NSData也可以做同样的事情,但这不是一个好主意。相反,应使用NSURLConnection异步下载映像,并且只有在完全下载映像后,才应将其转换为UIImage并分配给映像视图。遗憾的是,截至本文撰写之时,此功能不可用。。。相反,您必须通过以下方式自行实现功能:
@protocol EGOImageViewDelegate<NSObject>
@optional
- (void)imageViewLoadedImage:(EGOImageView*)imageView;
- (void)imageViewFailedToLoadImage:(EGOImageView*)imageView error:(NSError*)error;
@end
@protocol-egomageviewdelegate
@可选的
-(void)ImageViewLoadeImage:(EGOImageView*)imageView;
-(void)imageViewFailedToLoadImage:(EGOImageView*)imageView错误:(nError*)错误;
@结束
我正在使用的是一个设计精美的库,它有放置占位符图像的选项,无论是内存还是磁盘缓存图像,或者使用独立于UIImageView
的下载程序
我试着自己去做,但是图书馆把所有的痛苦都带走了
您只需为您的案例编写以下代码:
#import "UIImageView+WebCache.h"
[imageView sd_setImageWithURL:[NSURL URLWithString:@"http://www.domain.com/path/to/image.jpg"] placeholderImage:[UIImage imageNamed:@"placeholder.png"]];
这对我来说很有吸引力。另一个选项是Three20库中的TTImageView,它处理图像的异步加载。控制效果很好。然而,缺点是您必须处理安装Three20的噩梦(这几乎不可能完全删除)。如果您想在ImageView中显示Url中的图像,还希望将此图像保存在缓存中,以便优化到服务器的交互。这将帮助您将imageView对象和字符串Url传递给此函数
-(void)downloadingServerImageFromUrl:(UIImageView*)imgView AndUrl:(NSString*)strUrl{
strUrl = [strUrl encodeUrl];
NSString* theFileName = [NSString stringWithFormat:@"%@.png",[[strUrl lastPathComponent] stringByDeletingPathExtension]];
NSFileManager *fileManager =[NSFileManager defaultManager];
NSString *fileName = [NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"tmp/%@",theFileName]];
imgView.backgroundColor = [UIColor darkGrayColor];
UIActivityIndicatorView *actView = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
[imgView addSubview:actView];
[actView startAnimating];
CGSize boundsSize = imgView.bounds.size;
CGRect frameToCenter = actView.frame;
// center horizontally
if (frameToCenter.size.width < boundsSize.width)
frameToCenter.origin.x = (boundsSize.width - frameToCenter.size.width) / 2;
else
frameToCenter.origin.x = 0;
// center vertically
if (frameToCenter.size.height < boundsSize.height)
frameToCenter.origin.y = (boundsSize.height - frameToCenter.size.height) / 2;
else
frameToCenter.origin.y = 0;
actView.frame = frameToCenter;
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
NSData *dataFromFile = nil;
NSData *dataFromUrl = nil;
dataFromFile = [fileManager contentsAtPath:fileName];
if(dataFromFile==nil){
dataFromUrl=[[[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:strUrl]] autorelease];
}
dispatch_sync(dispatch_get_main_queue(), ^{
if(dataFromFile!=nil){
imgView.image = [UIImage imageWithData:dataFromFile];
}else if(dataFromUrl!=nil){
imgView.image = [UIImage imageWithData:dataFromUrl];
NSString *fileName = [NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"tmp/%@",theFileName]];
BOOL filecreationSuccess = [fileManager createFileAtPath:fileName contents:dataFromUrl attributes:nil];
if(filecreationSuccess == NO){
NSLog(@"Failed to create the html file");
}
}else{
imgView.image = [UIImage imageNamed:@"NO_Image.png"];
}
[actView removeFromSuperview];
[actView release];
[imgView setBackgroundColor:[UIColor clearColor]];
});
});
}
-(void)下载ServerImageFromURL:(UIImageView*)imgView和URL:(NSString*)strUrl{
strUrl=[strUrl encodeUrl];
NSString*theFileName=[NSString stringWithFormat:@“%@.png”,[[strUrl lastPathComponent]stringByDeletingPathExtension];
NSFileManager*fileManager=[NSFileManager defaultManager];
NSString*文件名=[NSHomeDirectory()stringByAppendingPathComponent:[NSString stringWithFormat:@“tmp/%@”,文件名]];
imgView.backgroundColor=[UIColor darkGrayColor];
UIActivityIndicatorView*actView=[[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
[imgView添加子视图:actView];
[actView startAnimating];
CGSize boundsSize=imgView.bounds.size;
CGRect frameToCenter=actView.frame;
//水平居中
if(frameToCenter.size.width
对于这样一个简单的任务,我强烈建议不要集成像Three20这样的项目,该库是一个怪物,启动和运行起来不是很简单
相反,我建议采用这种方法:
NSString *imageUrl = @"http://www.foo.com/myImage.jpg";
[NSURLConnection sendAsynchronousRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:imageUrl]] queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
myImageView.image = [UIImage imageWithData:data];
}];
为Swift 3.0编辑
*为Swift 2.0编辑
let request = NSURLRequest(URL: NSURL(string: urlString)!)
NSURLSession.sharedSession().dataTaskWithRequest(request) { (data, response, error) -> Void in
if error != nil {
print("Failed to load image for url: \(urlString), error: \(error?.description)")
return
}
guard let httpResponse = response as? NSHTTPURLResponse else {
print("Not an NSHTTPURLResponse from loading url: \(urlString)")
return
}
if httpResponse.statusCode != 200 {
print("Bad response statusCode: \(httpResponse.statusCode) while loading url: \(urlString)")
return
}
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.myImageView.image = UIImage(data: data!)
})
}.resume()
以下是最佳答案的更新答案,因为imageWithContentsOfURL不再是UIImage的方法。您必须使用CIImage:
NSURL *url = [NSURL URLWithString:@"http://url_goes_here.com/logo.png"];
imageView.image = [UIImage imageWithCIImage:[CIImage imageWithContentsOfURL:url]];
使用
AFNetworking
categoryUIImageView+AFNetworking.h
#import "UIImageView+AFNetworking.h
[profileImageView setImageWithURL:[NSURL URLWithString:photoURL] placeholderImage:[UIImage imageNamed:@"placeholder"]];
+正如你所说,这绝对是个坏主意。也就是说,您可以使用占位符图像,然后在后台启动NSURLConnection.Ok。多线程呢?有没有其他方法来设计一个动态应用程序,我的想法是在plist中阅读,并使用此列表中的链接来阅读图像并显示它。我不想每次网站更新时都要更新应用程序。@alJaree正如我建议的那样,你可以使用占位符图像并加载“c”
let request = NSURLRequest(URL: NSURL(string: urlString)!)
NSURLSession.sharedSession().dataTaskWithRequest(request) { (data, response, error) -> Void in
if error != nil {
print("Failed to load image for url: \(urlString), error: \(error?.description)")
return
}
guard let httpResponse = response as? NSHTTPURLResponse else {
print("Not an NSHTTPURLResponse from loading url: \(urlString)")
return
}
if httpResponse.statusCode != 200 {
print("Bad response statusCode: \(httpResponse.statusCode) while loading url: \(urlString)")
return
}
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.myImageView.image = UIImage(data: data!)
})
}.resume()
NSURL *url = [NSURL URLWithString:@"http://url_goes_here.com/logo.png"];
imageView.image = [UIImage imageWithCIImage:[CIImage imageWithContentsOfURL:url]];
#import "UIImageView+AFNetworking.h
[profileImageView setImageWithURL:[NSURL URLWithString:photoURL] placeholderImage:[UIImage imageNamed:@"placeholder"]];