简体   繁体   English

如何在iOS中使用URL和NSString在UIImageView上显示图像?

[英]How to display image on UIImageView using URL and NSString in ios?

I want to display image on UIImageView using URL and NSString . 我想使用URL和NSStringUIImageView上显示图像。 I am unable to show image. 我无法显示图像。

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(即; url_Img_FULL),然后传递到如下图像:

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. 我想要来自“ url_Img_FULL”(即:两个URL的组合)的图像将显示。 You can check also the url is working properly. 您也可以检查网址是否正常运行。 Any idea? 任何的想法?

    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. 尝试这个。

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]];
    });    
});

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
}

Get image from following code 从以下代码获取图像

NSData *imageUrl = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"Your image URL Here"]];

Then set image using following code 然后使用以下代码设置图像

[UIImage imageWithData:imageUrl];

尝试这个

NSString* combinedString = [stringUrl1 stringByAppendingString stringUrl2];

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 创建带有完成处理程序的方法以从您的网址获取图像数据

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.")

}
   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]];
    });    
});

try AsyncImageView for your this requirement see this example 根据您的要求尝试使用AsyncImageView,请参见以下示例

  1. AsyncImageView AsyncImageView

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. 网址字符串的最后。

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 ://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 : http://opensum.in/app_test_f1/45djx96.jpg

Change the code like: 更改代码,例如:

 NSString *url_Img1 = @"http://opensum.in/app_test_f1/";

It'll work. 会的

for showing image from url you can try this... 用于显示网址图片,您可以尝试以下操作...

 [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... 快乐的编码...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM