_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..
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];
}
Can you help me please. I would like to improve this code, possibly by utilizing NSURLSession? How would I change this code to use this construct?
The objective of the code is to load a small .png image in the background.
NSDate *myDate = (NSDate *)[[NSUserDefaults standardUserDefaults] objectForKey:#"LastUpdate"];
NSString *img=[NSString stringWithFormat:phpLinkgetUpdates, myDate];
NSURL *url = [NSURL URLWithString:[img stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSData *data = [[NSData alloc] initWithContentsOfURL:url];
UIImage *tmpImage = [[UIImage alloc] initWithData:data];
imgUpdate.image = tmpImage;
Thanks for your help!
For downloading the image you can use SDWebImage. It will download image and stored into the local cache memory.
Objective C:
#import <SDWebImage/UIImageView+WebCache.h>
...
[imageView sd_setImageWithURL:[NSURL URLWithString:IMAGE_URL
placeholderImage:[UIImage imageNamed:#"placeholder.png"]];
Swift:
import SDWebImage
imageView.sd_setImage(with: URL(string: IMAGE_URL), placeholderImage: UIImage(named: "placeholder.png"))
You use below code:
NSString *str = YOUR_IMAGE_URL;
NSString* encodedUrl = [str stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
NSURL *url = [NSURL URLWithString:encodedUrl];
NSURLSessionDataTask *downloadTask = [[NSURLSession sharedSession]
dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
{
UIImage *image = [UIImage imageWithData:data];
}];
[downloadTask resume];
I have a UIImageview in UICollectionview cell and parse the image data from api and add to UIImageview. Now everything is going perfect but there is some problem I face during scroll down, when I tried to scroll UICollectionview cell its going hang.
Now I need to use NSCache to download image and than add it to UIImage, but I am unable to do this task I am stuck somewhere in my code, I don't know where. Please look at my code.
-(UICollectionViewCell*)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
OneTimeCell *cell = (OneTimeCell*)[collectionView dequeueReusableCellWithReuseIdentifier:#"cell" forIndexPath:indexPath];
cell.selected = YES;
[collectionView selectItemAtIndexPath:indexPath animated:NO scrollPosition:UICollectionViewScrollPositionNone];
cell.productname.text = [[productname objectAtIndex:indexPath.row] objectForKey:#"product_name"];
cell.productnumber.text = [[productname objectAtIndex:indexPath.row] objectForKey:#"id"];
NSString *image = [[productname objectAtIndex:indexPath.row] objectForKey:#"image" ];
NSLog(#"image %#", image);
NSURL *baseURL = [NSURL URLWithString:#"http://dev1.brainpulse.org/ecoware1//app/webroot/img/uploads/Product/thumb/"];
NSURL *url = [NSURL URLWithString:image relativeToURL:baseURL];
NSData * imageData = [NSData dataWithContentsOfURL:url];
UIImage * productimage = [UIImage imageWithData:imageData];
NSURL *absURL = [url absoluteURL];
NSLog(#"absURL = %#", absURL);
if (productimage) {
cell.productimage.image = productimage;
}
else
{
cell.productimage.image = [UIImage imageNamed:#"icon_1.png"];
[self.imageDownloadingQueue addOperationWithBlock:^{
NSURL *url = [NSURL URLWithString:image relativeToURL:baseURL];
NSData * imageData = [NSData dataWithContentsOfURL:url];
UIImageView *image = nil;
if (image) {
[self.imageCache setObject:image forKey:imageData];
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
OneTimeCell *cell =[collectionView cellForItemAtIndexPath:indexPath];
if (cell) {
cell.productimage.image = image;
}
}];
}
}];
}
return cell;
}
in your code line 10 you fetching image on mainthread that is why your cell got stuck . . .Please replace that code with this one
Replace this code
NSString *image = [[productname objectAtIndex:indexPath.row] objectForKey:#"image" ];
NSLog(#"image %#", image);
NSURL *baseURL = [NSURL URLWithString:#"http://dev1.brainpulse.org/ecoware1//app/webroot/img/uploads/Product/thumb/"];
NSURL *url = [NSURL URLWithString:image relativeToURL:baseURL];
NSData * imageData = [NSData dataWithContentsOfURL:url];
UIImage * productimage = [UIImage imageWithData:imageData];
NSURL *absURL = [url absoluteURL];
NSLog(#"absURL = %#", absURL);
With This one
NSString *image = [[productname objectAtIndex:indexPath.row] objectForKey:#"image" ];
NSLog(#"image %#", image);
NSURL *baseURL = [NSURL URLWithString:#"http://dev1.brainpulse.org/ecoware1//app/webroot/img/uploads/Product/thumb/"];
NSURL *url = [NSURL URLWithString:image relativeToURL:baseURL];
dispatch_queue_t q = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
dispatch_async(q, ^{
NSData * imageData = [NSData dataWithContentsOfURL:url];
dispatch_async(dispatch_get_main_queue(), ^{
UIImage * productimage = [UIImage imageWithData:imageData];
});
});
NSURL *url = #"................";
ImageRequest *request = [[ImageRequest alloc] initWithURL:url];
UIImage *image = [request cachedResult];
if (image) {
// Set the image if exist
} else {
[request startWithCompletion:^(UIImage *image, NSError *error) {
dispatch_async(dispatch_get_main_queue(), ^{
if(image) {
cell.productimage.image = productimage;
}else {
// Set any placeholder image here.......
}
});
}];
}
NSString *image = [[productname objectAtIndex:indexPath.row] objectForKey:#"image" ];
NSLog(#"image %#", image);
NSURL *baseURL = [NSURL URLWithString:#"http://dev1.brainpulse.org/ecoware1//app/webroot/img/uploads/Product/thumb/"];
NSURL *url = [NSURL URLWithString:image relativeToURL:baseURL];
dispatch_queue_t q = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
dispatch_async(q, ^{
//NSData * imageData = [NSData dataWithContentsOfURL:url];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:[NSURLRequest requestWithURL:url] queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
if(data)
{
dispatch_async(dispatch_get_main_queue(), ^{
UIImage * productimage = [UIImage imageWithData:data];
});
}
}];
});
I am getting image From JSON url.I tried like this but i did't not get image
NSMutableArray *al=[NSJSONSerialization JSONObjectWithData:webData options:0 error:nil];
NSLog(#"all NSMutable2%#",al);
NSDictionary *dict = [al objectAtIndex:1];
NSString *title=[dict objectForKey:#"dealimage"];
NSLog(#"all DIC%#",title);
NSData *data1 = [[NSData alloc] initWithData:[NSData
dataFromBase64String:title]];
NSLog(#"********************************%#",data1);
NSData* data = [Base64 decode:title ];
UIImage *image = [UIImage imageWithData:data];
dig=[[UIImageView alloc]initWithImage:image];
[self.view addSubview:dig];
dig.frame = CGRectMake(0, 25 , 150,150);
My idea is first NSString data converted to NSData and Then NSData pass to UIImage.But No luck
So Please give me any idea
#import "NSData+Base64.h"
//Creating the data from your base64String
NSData *data = [[NSData alloc] initWithData:[NSData dataFromBase64String: title]];
//Now data is decoded. You can convert them to UIImage
UIImage *image = [UIImage imageWithData:data];
dig=[[UIImageView alloc]initWithImage:image];
dig.frame = CGRectMake(0, 25 , 150,150);
[self.view addSubview:dig];
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]]];