[英]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.