[英]iOS Loading an Image from a URL
当我从URL将UIImage加载到iPhone上的UIImageView时遇到一些问题。 当我使用对象的属性生成NSURL(在NSURL的URLWithString方法的参数中带有URL)时,根本不会检索图像,但是,如果我对相同的URL进行硬编码,则会按预期检索并显示图像。
[item valueForKey:@“ pictureLocation”]; 下面的部分似乎是导致问题的原因,因为即使将两个硬编码的字符串连接在一起,NSURl的生成也没有问题。
NSString * imagePath = @"http://localhost:3000";
NSString * specificPath = (NSString *)[item valueForKey:@"pictureLocation"] ;
//concatenate the strings to get a fully formed URL
NSString * finalPath = [imagePath stringByAppendingString:specificPath];
UIImage *img = [[UIImage imageWithData: [NSData dataWithContentsOfURL: [NSURL URLWithString:finalPath]]] retain];
本质上,当我NSLog the finalPath并将该URL硬编码到程序中时,我得到了预期的结果。
为什么会这样呢?
valueForKey:
返回的NSString
是如何形成的? 是“ image.png”还是“ /image.png”? 如果是前者,则需要使用stringByAppendingPathComponent:
而不是stringByAppendingString:
您需要使用UIWebView并在其中加载html <img />
。 至少这是一个不错的解决方法。
在此处检查代码http://blog.timeister.com/2009/07/18/iphone-show-online-image/
- (void)loadImage:(NSString*)url frame:(CGRect)frame {
NSString* textHTML = @"
<html><head>
<style type=\"text/css\">
body {
background-color: transparent;
color: white;
}
</style>
</head><body style=\"margin:0\">
<img src=\"%@\" width=\"%0.0f\" height=\"%0.0f\"></img>
</body></html>";
NSString* html = [NSString stringWithFormat:textHTML, url, frame.size.width, frame.size.height];
if(webView == nil) {
webView = [[UIWebView alloc] initWithFrame:frame];
[self.view addSubview:webView];
}
[webView loadHTMLString:html baseURL:nil];
}
阿德里安
我认为问题与正确的编码有关。
尝试使用以下函数对参数进行正确编码:
encodedparams = [params stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
因此,在您的情况下:
NSString * specificPath = (NSString *)[item valueForKey:@"pictureLocation"] ;
specificPath = [specificPath stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
我认为这可以解决您的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.