Reputation: 264
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?
Upvotes: 7
Views: 47955
Reputation: 1451
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]];
});
});
Upvotes: 1
Reputation: 21
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
}
Upvotes: 2
Reputation: 4425
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.")
}
Upvotes: 0
Reputation: 1668
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.
Upvotes: 33
Reputation: 31083
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]];
});
});
Upvotes: 12
Reputation: 363
Get image from following code
NSData *imageUrl = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"Your image URL Here"]];
Then set image using following code
[UIImage imageWithData:imageUrl];
Upvotes: 1
Reputation: 219
try this
NSString* combinedString = [stringUrl1 stringByAppendingString stringUrl2];
Upvotes: 1
Reputation: 871
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...
Upvotes: 0
Reputation: 107121
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.
Upvotes: 0
Reputation: 20541
try AsyncImageView for your this requirement see this example
Upvotes: 0