如何在 ios 中使用 URL 和 NSString 在 UIImageView 上显示图像?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13528244/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to display image on UIImageView using URL and NSString in ios?
提问by Areeba Khan
I want to display image on UIImageView
using URL and NSString
. I am unable to show image.
我想在UIImageView
使用 URL 和NSString
. 我无法显示图像。
My code is:
我的代码是:
UIImageView *view_Image = [[UIImageView alloc]initWithFrame:CGRectMake(view_Image_Pos_X, view_Image_Pos_Y, 179, 245)];
view_Image.backgroundColor = [UIColor greenColor];
view_Image.tag = img;
view_Image.userInteractionEnabled=YES;
view_Image.autoresizesSubviews = YES;
view_Image.alpha = 0.93;
[self.view addSubview:view_Image];
Here what i am trying:
这是我正在尝试的:
if (img == 0) {
NSString *url_Img1 = @"http://opensum.in/app_test_f1/;";
NSString *url_Img2 = @"45djx96.jpg";
NSString *url_Img_FULL = [NSString stringWithFormat:@"%@%@", url_Img1,url_Img2];
NSLog(@"Show url_Img_FULL: %@",url_Img_FULL);
NSURL *url_img = [NSURL URLWithString:url_Img_FULL];
NSLog(@"Show: url_img %@",url_img);
// Here below line working perfectly and image is showing
view_Image.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://opensum.in/app_test_f1/45djx96.jpg"]]]; // working code
but i dont want this i want to concatanate two url make one url(ie;url_Img_FULL) and then pass to an image like below:
但我不想要这个我想连接两个 url 生成一个 url(ie;url_Img_FULL) 然后传递给如下图像:
UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:url_Img_FULL]]]; // Not Working
UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:url_Img_FULL]]]; // Not Working
I Want from "url_Img_FULL" (ie: combination of two url) The image will show. You can check also the url is working properly. Any idea?
我想要从“url_Img_FULL”(即:两个 url 的组合)图像将显示。您还可以检查网址是否正常工作。任何的想法?
回答by Nookaraju
NSString *url_Img1 = @"http://opensum.in/app_test_f1";
NSString *url_Img2 = @"45djx96.jpg";
NSString *url_Img_FULL = [url_Img1 stringByAppendingPathComponent:url_Img2];
NSLog(@"Show url_Img_FULL: %@",url_Img_FULL);
view_Image.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:url_Img_FULL]]];
try this.
尝试这个。
回答by Rajneesh071
Just do it
去做就对了
NSString *imgURL = @"imagUrl";
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:imgURL]];
[YourImgView setImage:[UIImage imageWithData:data]];
Using GCD :If you don't want to hang your application then you can download your image in background.
使用 GCD :如果您不想挂起您的应用程序,那么您可以在后台下载您的图像。
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSString *imgURL = @"imagUrl";
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:imgURL]];
//set your image on main thread.
dispatch_async(dispatch_get_main_queue(), ^{
[YourImgView setImage:[UIImage imageWithData:data]];
});
});
回答by Manish Khandelwal
For Swift 3.0
对于 Swift 3.0
class ImageLoader {
var cache = NSCache<AnyObject, AnyObject>()
class var sharedLoader : ImageLoader {
struct Static {
static let instance : ImageLoader = ImageLoader()
}
return Static.instance
}
func imageForUrl(urlString: String, completionHandler:@escaping (_ image: UIImage?, _ url: String) -> ()) {
DispatchQueue.global().async {
let data: NSData? = self.cache.object(forKey: urlString as AnyObject) as? NSData
if let goodData = data {
let image = UIImage(data: goodData as Data)
DispatchQueue.main.async {
completionHandler(image, urlString)
}
return
}
let url:NSURL = NSURL(string: urlString)!
let task = URLSession.shared.dataTask(with: url as URL) {
data, response, error in
if (error != nil) {
print(error?.localizedDescription)
completionHandler(nil, urlString)
return
}
if data != nil {
let image = UIImage(data: data!)
self.cache.setObject(data as AnyObject, forKey: urlString as AnyObject)
DispatchQueue.main.async {
completionHandler(image, urlString)
}
return
}
}
task.resume()
}
}
}
Usage
用法
ImageLoader.sharedLoader.imageForUrl(urlString: imageUrl as! String) { (image, url) in
self.imageView.image = image
}
回答by Dilip Tiwari
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSString *str = self.recordlarge[@"images"];
NSLog(@"Project Gallery id Record : %@",str);
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:str]];
dispatch_async(dispatch_get_main_queue(), ^{
[self.myimagelarge setImage:[UIImage imageWithData:data]];
});
});
回答by Ali Majeed
try this
尝试这个
NSString* combinedString = [stringUrl1 stringByAppendingString stringUrl2];
回答by Moin Shirazi
For Swift 3.0
对于 Swift 3.0
Synchronously:
同步:
if let filePath = Bundle.main().pathForResource("imageName", ofType: "jpg"), image = UIImage(contentsOfFile: filePath) {
imageView.contentMode = .scaleAspectFit
imageView.image = image
}
Asynchronously:
异步:
Create a method with a completion handler to get the image data from your url
创建一个带有完成处理程序的方法以从您的 url 获取图像数据
func getDataFromUrl(url:URL, completion: ((data: Data?, response: URLResponse?, error: NSError? ) -> Void)) {
URLSession.shared().dataTask(with: url) {
(data, response, error) in
completion(data: data, response: response, error: error)
}.resume()
}
Create a method to download the image (start the task)
创建下载镜像的方法(启动任务)
func downloadImage(url: URL){
print("Download Started")
getDataFromUrl(url: url) { (data, response, error) in
DispatchQueue.main.sync() { () -> Void in
guard let data = data where error == nil else { return }
print(response?.suggestedFilename ?? url.lastPathComponent ?? "")
print("Download Finished")
self.imageView.image = UIImage(data: data)
}
}
}
Usage:
用法:
override func viewDidLoad() {
super.viewDidLoad()
print("Begin of code")
if let checkedUrl = URL(string: "http://www.apple.com/euro/ios/ios8/a/generic/images/og.png") {
imageView.contentMode = .scaleAspectFit
downloadImage(url: checkedUrl)
}
print("End of code. The image will continue downloading in the background and it will be loaded when finished.")
}
Extension:
延期:
extension UIImageView {
func downloadedFrom(link: String, contentMode mode: UIViewContentMode = .scaleAspectFit) {
guard let url = URL(string: link) else { return }
contentMode = mode
URLSession.shared().dataTask(with: url) { (data, response, error) in
guard
let httpURLResponse = response as? HTTPURLResponse where httpURLResponse.statusCode == 200,
let mimeType = response?.mimeType where mimeType.hasPrefix("image"),
let data = data where error == nil,
let image = UIImage(data: data)
else { return }
DispatchQueue.main.sync() { () -> Void in
self.image = image
}
}.resume()
}
}
Usage:
用法:
override func viewDidLoad() {
super.viewDidLoad()
print("Begin of code")
imageView.downloadedFrom(link: "http://www.apple.com/euro/ios/ios8/a/generic/images/og.png")
print("End of code. The image will continue downloading in the background and it will be loaded when finished.")
}
回答by Mohd Kalimullah Sheikh
Get image from following code
从以下代码获取图像
NSData *imageUrl = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"Your image URL Here"]];
Then set image using following code
然后使用以下代码设置图像
[UIImage imageWithData:imageUrl];
回答by Paras Joshi
try AsyncImageView for your this requirement see this example
尝试 AsyncImageView 来满足您的这个要求,请参阅此示例
回答by Midhun MP
I tested your url and found the issue.
我测试了您的网址并发现了问题。
The issue is with this line:
问题出在这一行:
NSString *url_Img1 = @"http://opensum.in/app_test_f1/;";
You are adding a ;
at last of the url string.
您;
在 url 字符串的最后添加了一个。
So when you concatinate two strings it'll look like: http://opensum.in/app_test_f1/;45djx96.jpg
所以当你连接两个字符串时,它看起来像: http://opensum.in/app_test_f1/;45djx96.jpg
That is not a valid url.
这不是一个有效的网址。
The correct url is : http://opensum.in/app_test_f1/45djx96.jpg
正确的网址是: http://opensum.in/app_test_f1/45djx96.jpg
Change the code like:
更改代码如下:
NSString *url_Img1 = @"http://opensum.in/app_test_f1/";
It'll work.
它会工作。
回答by Bhrigesh
for showing image from url you can try this...
要显示来自 url 的图像,您可以试试这个...
[ImageViewname setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",your url]]];
for showing image locally from app you can try this....
要从应用程序本地显示图像,您可以试试这个....
ImageViewname.image = [UIImage imageNamed:@"test.png"];
I hope this will help you.
我希望这能帮到您。
happy coding...
快乐编码...