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

后端 未结 10 1953
孤城傲影
孤城傲影 2021-01-02 16:49

I want to display image on UIImageView using URL and NSString. I am unable to show image.

My code is:

UIImageView *view_Im         


        
相关标签:
10条回答
  • 2021-01-02 17:19
       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]];
        });    
    });
    
    0 讨论(0)
  • 2021-01-02 17:21

    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.

    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]];
        });    
    });
    
    0 讨论(0)
  • 2021-01-02 17:22

    Get image from following code

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

    Then set image using following code

    [UIImage imageWithData:imageUrl];
    
    0 讨论(0)
  • 2021-01-02 17:26

    For 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.")
    
    }
    
    0 讨论(0)
提交回复
热议问题