7

I want to display image on UIImageView using URL and NSString. 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:

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?

2
  • 1
    NSString *url_Img1 = @"http://opensum.in/app_test_f1/;"; your URL ends with ";" Commented Nov 23, 2012 at 11:36
  • 1
    you have a semicolon at the end of the value of url_Img1, I guess this is the problem Commented Nov 23, 2012 at 11:36

9 Answers 9

33
    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.

Sign up to request clarification or add additional context in comments.

3 Comments

Nice, this worked but now I am trying to create a scanner that will scan web pages and show me the first image it scans.
Can't the OP literrally just do NSString *url_Img_FULL = [NSString stringWithFormat:@"%@%@", url_Img1, url_Img2]; ??
You can do it but this code will fetching image on main thread and make bad performance. It's just for practicing, you can't apply it for any project. You should use AFNetworking or SDWebImage
12

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

Comments

2

For 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
}

Comments

1

try this

NSString* combinedString = [stringUrl1 stringByAppendingString stringUrl2];

Comments

1

Get image from following code

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

Then set image using following code

[UIImage imageWithData:imageUrl];

Comments

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

Comments

0

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

That is not a valid url.

The correct url is : http://opensum.in/app_test_f1/45djx96.jpg

Change the code like:

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

It'll work.

3 Comments

Thanks i corrected. But still not working-> view_Image.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:url_Img_FULL"]]];
@AreebaKhan: check that your view_Image is not nil
@AreebaKhan: are you setting image to view_Image in the same method ?
0

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

Comments

0

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

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.