This is my JSON response,
{
"AppConfig": {
"store_logo": "url",
"deal_status": "A",
"see_the_menu_btn": "A",
"store_id": "3",
"store_name": " Pizza Restaurant",
"bg_image": "www.my image.png"
}
}
NSString *localwthr = [NSString stringWithFormat:#"my url"];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:localwthr]];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
if (responsedata) {
NSDictionary *Dictionarydetails = [NSJSONSerialization
JSONObjectWithData:responsedata
options:kNilOptions
error:nil];
NSLog(#"The return data is: %#",Dictionarydetails);
NSString *imgURL=[[Dictionarydetails objectForKey:#"AppConfig"]objectForKey:#"bg_image"];
UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0,0,100,100)];
imageView.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString: imgURL]]];
}
}
I need to get URL value for key bg_image, download image and set it in the UIImageView. How can I do this?
imageUrl is never like "www.my image.png",
imageUrl is like "http://www.serverName.com/directory/..../imageName.png"
if there is space in your url then you have to convert it into UTF8 format, which is a standard format for webURL.
so You should use,
imgURL = [imgURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//Use it as it shown in below code.
NSString *imgURL=[[jsonDict objectForKey:#"AppConfig"]objectForKey:#"bg_image"];
imgURL = [imgURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]
UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString: imgURL]]];
cheers!
For loading the image from the URL, then
NSString *imgURL=[[jsonDict objectForKey:#"AppConfig"]objectForKey:#"bg_image"];
UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString: imgURL]]];
Try This:
NSString *imgURL=[[jsonDict objectForKey:#"AppConfig"]objectForKey:#"bg_image"];
UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0,0,100,100)];
imageView.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString: imgURL]]];
check out this code , is this you are needed or not as rmaddy told post your done code as far as now
NSString *imageName=[[jsonDict objectForKey:#"AppConfig"]objectForKey:#"bg_image"];
imageview.image=[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString: imageName]]];
Related
I am uploading the image from the ImagePicker and once the image is upload on the server I show it from URL. So from local image to URL image, there comes a blink, which I want to avoid but I am unable to fix it. Any suggestion will be really helpful. I am adding the code below:
- (void)setDataOnCell:(NSDictionary *)dict {
self.messageTimeLabel.text = [CommonUtils checkForNUllValue:[dict valueForKey:#"msg_time"]];
if (![[CommonUtils checkForNUllValue:[dict valueForKey:#"msg_status"]] isEqualToString:#"Read"]) {
self.messageTickImageView.image = [UIImage imageNamed:#"check_delivered_icon"];
self.messageStatusLabel.textColor = [UIColor colorWithRed:166.0f/255.0f green:166.0f/255.0f blue:166.0f/255.0f alpha:1.0];
}
else {
self.messageTickImageView.image = [UIImage imageNamed:#"check_read_icon"];
self.messageStatusLabel.textColor = [UIColor colorWithRed:254.0f/255.0f green:223.0f/255.0f blue:224.0f/255.0f alpha:1.0];
}
self.messageStatusLabel.text = [CommonUtils checkForNUllValue:[dict valueForKey:#"msg_status"]];
if ([[NSString stringWithFormat:#"%#", [dict valueForKey:#"attachment_type"]] isEqualToString:#"local_img"]){
self.messageImageview.image = [dict valueForKey:#"attachment"];
}
else {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),
^{
NSURL *imageURL = [NSURL URLWithString:[NSString stringWithFormat:#"%#", [NSString stringWithFormat:#"%#", [dict valueForKey:#"attachment"]]]];
NSData *urlData = [NSData dataWithContentsOfURL:imageURL];
//This is your completion handler
dispatch_sync(dispatch_get_main_queue(), ^{
UIImage *image = [UIImage imageWithData:urlData];
self.messageImageview.image = image;
});
});
}
}
first of all you need to set a default image on this image view after that you call image by url and set on this
NSOperationQueue *queueThumbnl = [[NSOperationQueue alloc] init];
[queueThumbnl setMaxConcurrentOperationCount:NSOperationQueueDefaultMaxConcurrentOperationCount];
[queueThumbnl addOperationWithBlock:^{
// Background work
NSURL *imageURL = [NSURL URLWithString:[NSString stringWithFormat:#"%#", [NSString stringWithFormat:#"%#", [dict valueForKey:#"attachment"]]]];
NSData *urlData = [NSData dataWithContentsOfURL:imageURL];
UIImage *image = [UIImage imageWithData:urlData];
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:self.messageImageview, #"messageImageview", urlData, #"imageData", nil];
[self performSelectorOnMainThread:#selector(mainThreadUIUpdate:) withObject:dict waitUntilDone:YES];
// [self updateThumbnailOnMainThread:anItem setImageTo:cell];
}];
-(void)mainThreadUIUpdate:(NSDictionary *)dict
{
UIImageView *messge = [dict objectForKey:#"messageImageview"];
UIImage *image = [dict objectForKey:#"image"];
[messge.imageView setImage:image];
[cell.imageView setNeedsDisplay:YES];
}
I'm using the below to set my imageView with a url (located in path). Yes, the URL data is returned successfully, but for some reason, my imageView remains blank (just white?)
And yes, I've hooked up my imageView property... Any idea what's wrong? Should I be using a different block of code to accomplish this?
Viewcontroller.m
NSMutableDictionary *viewParamsDogs = [NSMutableDictionary new];
[viewParamsDogs setValue:#"mydogs" forKey:#"view_name"];
[DIOSView viewGet:viewParamsDogs success:^(AFHTTPRequestOperation *operation, id responseObject) {
self.dogData = [responseObject mutableCopy];
[operation responseString];
NSDictionary *dic = [responseObject valueForKey: #"field_pet_photo_path"];
NSArray *arr = [dic valueForKey: #"und"];
NSDictionary *dic2= [arr objectAtIndex : 0];
NSString *path = [NSString stringWithFormat:#"%#", [dic2 valueForKey: #"safe_value"]];
NSLog(#"This is path %#", path);
if([path length]>0) {
NSURL *url = [NSURL URLWithString:path];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *image = [UIImage imageWithData:data];
self.dogimageView.image = image;
} else {
NSString *ImageURL = #"http://url.ca/paw.png";
NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:ImageURL]];
self.dogimageView.image = [UIImage imageWithData:imageData];
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Failure: %#", [error localizedDescription]);
}];
Path:
[5111:1673330] This is path (
"http://url.com/default/files/stored/1460659054.jpg"
)
NSLog(#"This is path %#, %#", path, NSStringFromClass(path.class)); returns:
2016-04-14 13:18:39.590 [5225:1700657] This is path (
"http://url.com/default/files/stored/1460659054.jpg"
), __NSCFString
I recommend usage of AFNetworking https://github.com/AFNetworking/AFNetworking for all networking connect features.
Import UIImageView+AFNetworking.h at beginning of file
#import "UIImageView+AFNetworking.h"
Get path from dic2
NSString *path = dic2[#"safe_value"];
Check if path is a string
if (![path isKindOfClass:[NSString class]]) {
return;
}
Create a NSURL object from string
NSURL *imageUrl = [NSURL URLWithString:path];
Set imageUrl to UIImageView
[self.dogimageView setImageWithURL:imageUrl];
You could check the full code in my gist https://gist.github.com/MaciejGad/fa8cb80dfc73ea55edeedb75418ea2ec
Edit:
the reason of error was the path that was set as:
NSString *path = #"(
\"http://url.com/default/files/stored/1460659054.jpg\"
)";
to change to normal URL we need to trim it:
NSMutableCharacterSet *characterSetToTrim = [NSMutableCharacterSet characterSetWithCharactersInString:#"()\""];
[characterSetToTrim formUnionWithCharacterSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
path = [path stringByTrimmingCharactersInSet:characterSetToTrim];
after this trimming path should be http://url.com/default/files/stored/1460659054.jpg
Try like this,
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *image = [UIImage imageWithData:data];
self.dogimageView.image = [[UIImageView alloc] initWithImage:image];
and You can use great library SDWebImage for caching image. When image comes from server use of this library is very helpful. Hope this will work.
Update :
NSString *path = [NSString stringWithFormat:#"%#", [dic2 valueForKey: #"safe_value"]];
NSURL *url = [NSURL URLWithString:path];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *image = [UIImage imageWithData:data];
self.dogimageView.image = [[UIImageView alloc] initWithImage:image];
Try this. :)
Try using dataWithContentsOfURL:options:error: instead and look if there is any error message there
_pageImages is nsmutableArry I'm store the image url.
_pageImages = [[NSMutableArray alloc]initWithObjects:#"https://api.url2png.com/v3/P4DE5D1C99D8EF/7bbb6e0d1b74fb0ae1d4f18b06320096/400x400/abc.com",#"https://api.url2png.com/v3/P4DE5D1C99D8EF/7bbb6e0d1b74fb0ae1d4f18b06320096/400x400/abc.com", nil];
Want to display this url images in uiimageview.
NSURL *url = [NSURL URLWithString:[_pageImages objectAtIndex:i]];
NSData *data = [[NSData alloc] initWithContentsOfURL:url];
UIImage *tmpImage = [UIImage imageWithData:data];
_backgroundImageView.frame = CGRectMake(0 ,10, 320, 320);
_backgroundImageView.image = tmpImage;
[self.view addSubview:_backgroundImageView];
I saw many examples but i can't get the proper solution. new for development. help me..
The problem is in the URL!
Try to access your images URL, all I got is "Unauthorized".
Run this sample code, your code, just using a different image address.
Check for the correct image address, and it should run as expected.
NSMutableArray *pageImages = [[NSMutableArray alloc]initWithObjects:#"http://findicons.com/files/icons/1636/file_icons_vs_3/128/url.png",#"http://findicons.com/files/icons/1636/file_icons_vs_3/128/pdf.png", nil];
NSURL *url = [NSURL URLWithString:[pageImages objectAtIndex:0]];
NSData *data = [[NSData alloc] initWithContentsOfURL:url];
UIImage *tmpImage = [UIImage imageWithData:data];
_depImage.frame = CGRectMake(0 ,10, 320, 320);
_depImage.image = tmpImage;
try this by sending AsynchronousRequest for image downloading--
NSURL *url = [NSURL URLWithString:[_pageImages objectAtIndex:i]];
[NSURLConnection sendAsynchronousRequest:[NSURLRequest requestWithURL:url] queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
_backgroundImageView.image = [UIImage imageWithData:data];
}];
We can simply use following to Load Image data from URL
_backgroundImageView.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLwithString:urlString]]];
No need of Calling a service call here.
Hope it helps..
In my app, Im using an API to get images from a server. Using the below code, it gets the images in order of size to replace themselves with better quality.
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSURL *imageURL = [NSURL URLWithString: [NSString stringWithFormat:#"%#", [[[self.information objectForKey:#"images"]objectForKey:#"normal"] description]]];
NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
self.shotImage = [UIImage imageWithData:imageData];
self.image.image = self.shotImage;
});
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSURL *imageURL = [NSURL URLWithString: [NSString stringWithFormat:#"%#", [[[self.information objectForKey:#"images"]objectForKey:#"hidpi"] description]]];
NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
UIImage *image = [UIImage imageWithData:imageData];
self.image.image = self.shotImage;
});
Also, if you press on the image it then takes you too another ViewController where the image is fullscreen.
However, even if I wait for the high quality one to load before I tap on it, in the PrepareForSegue Method, it still only passes the original low quality version.
See code below from PrepareForSegue
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
FullSizeImageViewController *vc = [segue destinationViewController];
UIImage *img = [[UIImage alloc] init];
img = self.shotImage;
vc.shotImage = img;
}
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSURL *imageURL = [NSURL URLWithString: [NSString stringWithFormat:#"%#", [[[self.information objectForKey:#"images"]objectForKey:#"hidpi"] description]]];
NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
UIImage *image = [UIImage imageWithData:imageData];
self.image.image = self.shotImage;
});
In this code looks like you miss this line:
self.shotImage = [UIImage imageWithData:imageData];
I tried fetching the image location but its not displaying it in UIImageView, the code which is used for fetching is,
in class.h file,
#property (strong, nonatomic) IBOutlet UIImageView *imageview;
class.m file,
NSString *imagee;
imagee = [result objectForKey:#"image"];
NSLog(#"image is %# \n",imagee);
the 'imagee' string could return the exact url for the image.
code for image displaying is,
UIImage *imagevieww = [UIImage imageNamed:[result objectForKey:#"image"]];
imageview.image = imagevieww;
but at final i could get the empty space where the image should be placed.
Found the answer for my problem, thanks for everyone who helped me to find this answer.
UPDATED: Include 'http' with the urlstring so that, it can fetch the correct image from the webservice.
NSString *urlString = [NSString stringWithFormat:#"http://%#",[result objectForKey:#"image"]];
NSLog(#"url image is %# \n",urlString);
NSData *imageData = [[NSData alloc] init];
imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlString]];
NSLog(#"image data is %#",imageData);
imageview.image = [UIImage imageWithData:imageData];
The UIImage method imageNamed: is used to load image present locally. In your case you need to download the image from the URL. There are various ways to do this based on requirement.
Easiest one is,
//URL encode the string
NSString *url = [[result objectForKey:#"image"] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]];
imageview.image = [UIImage imageWithData:imageData];
This will download the image synchronously and on the main thread(if called from main thread). You want to do this asynchronously on background thread. Usually dispatch_async(GCD) is used for doing this.
Hope that helps!
If 'imagee' returned exact url , then fetch the image from web service should be like this.
imageview.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[result objectForKey:#"image"]]]];
Try this
NSString *imageString = [NSString stringWithFormat:#"data:image/jpg;base64,%#",[yourDict objectForKey:#"ImageString"]];
NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:imageString]];
UIImage *image = [UIImage imageWithData:imageData];
.h
#property (strong, nonatomic) IBOutlet UIImageView *imageView;
.m
Get Image From Webservices:
NSURL *url = [NSURL URLWithString:#"http://www.site.com/image.jpg"];
NSData *myImageData = [NSData dataWithContentsOfURL:url];
UIImage *image = [[UIImage alloc] initWithData:myImageData];
Set Image to ImageView:
imageView.image = image;
I did the following and it works for me.
NSURL *url = [NSURL URLWithString:#"http://www.yourdomain.com/imagename.png"];
NSData *myData = [NSData dataWithContentsOfURL:url];
UIImage *image = [[UIImage alloc] initWithData:myData];
["%storyboardImageName%" setImage:image];
Please note that storyboardImagename is the variable that you put on the xib or storyboard. You will need to change it. Also note the 'setImage' attribute which actually ties it together.
Hope this helps.
Convert the URL into UIImage,
Try This:
NSURL *url = [NSURL URLWithString:#"http://yoursite.com/imageName.png/jpg"];
NSData *myData = [NSData dataWithContentsOfURL:url];
UIImage *image = [[[UIImage alloc] initWithData:myData] autorelease];
Use this image on imageview. If you are getting problem then try to download the image in background.
Follow this Link