How can i add local image.png to cell if image not load from url?
- (UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *CellIdentifier = #"Cell";
DetailCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
NSURL* url = [NSURL URLWithString:[arrayOfImages objectAtIndex:indexPath.row]];
NSURLRequest* request = [NSURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse * response,
NSData * imagedata,
NSError * error) {
if (!error){
UIImage* image = [[UIImage alloc] initWithData:imagedata];
cell.flowerImage.image = image;
}
}];
return cell;
}
arrayOfImages - array of url strings that i've parsed from json.
You can check the image against nil to verify the image url.
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse * response,
NSData * imagedata,
NSError * error) {
if (!error){
UIImage* image = [[UIImage alloc] initWithData:imagedata];
if(!image) {
cell.flowerImage.image = [UIImage imageNamed:#"localImage"]; //local bundle image.
} else
cell.flowerImage.image = image;
} else {
cell.flowerImage.image = [UIImage imageNamed:#"localImage"];//local bundle image.
}
}];
Related
So I have this method to download an image from imgur.com as shown below:
- (void)getImageForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSURL *url=[NSURL URLWithString:[NSString stringWithFormat:#"i.imgur.com/%#.jpg",
[self.IDArray objectAtIndex:indexPath.row]]];
NSData * imageData = [[NSData alloc] initWithContentsOfURL:url];
self.imageTest = [UIImage imageWithData: imageData];
}
and then log the size of the data with this:
NSLog(#"%lx", (unsigned long)imageData.length);
but the size of the image in the log says
0
previously I use this asynchronous method:
- (void)getImageForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSURL *url=[NSURL URLWithString:[NSString stringWithFormat:#"i.imgur.com/%#.jpg",
[self.IDArray objectAtIndex:indexPath.row]]];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:urlRequest
queue:[NSOperationQueue currentQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
UIImage *imageMain = [UIImage imageWithData:data];
self.imageTest = [[UIImage alloc] init];
self.imageTest = [self imageWithImage:imageMain forRowAtIndexPath:indexPath];
}];
self.imageTest = [UIImage imageWithData: imageData];
}
but the log also says 0
yes the url exist. I have log it in another another method it is: i.imgur.com/EXtwoxT
What did I do wrong? how do I check that the image has been downloaded properly?
So I have this method to download an image from imgur.com as shown below:
- (void)getImageForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSURL *url=[NSURL URLWithString:[NSString stringWithFormat:#"i.imgur.com/%#.jpg",
[self.IDArray objectAtIndex:indexPath.row]]];
NSData * imageData = [[NSData alloc] initWithContentsOfURL:url];
self.imageTest = [UIImage imageWithData: imageData];
}
and then log the size of the data with this:
NSLog(#"%lx", (unsigned long)imageData.length);
but the size of the image in the log says
0
previously I use this asynchronous method:
- (void)getImageForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSURL *url=[NSURL URLWithString:[NSString stringWithFormat:#"i.imgur.com/%#.jpg",
[self.IDArray objectAtIndex:indexPath.row]]];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:urlRequest
queue:[NSOperationQueue currentQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
UIImage *imageMain = [UIImage imageWithData:data];
self.imageTest = [[UIImage alloc] init];
self.imageTest = [self imageWithImage:imageMain forRowAtIndexPath:indexPath];
}];
self.imageTest = [UIImage imageWithData: imageData];
}
but the log also says 0
yes the url exist. I have log it in another another method it is: i.imgur.com/EXtwoxT you can see for yourself
What did I do wrong? how do I check that the image has been downloaded properly?
EDIT :
for those who says it's the URL you can see my actual log below. you can copy&paste the URL in your browser to see if it exist (it does)
- (void)getImageForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSURL *url=[NSURL URLWithString:[NSString stringWithFormat:#"i.imgur.com/%#.jpg",
[self.IDArray objectAtIndex:indexPath.row]]];
NSLog(#"i.imgur.com/%#.jpg", [self.IDArray objectAtIndex:indexPath.row]);
//Asynchronous handler
// NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
// [NSURLConnection sendAsynchronousRequest:urlRequest
// queue:[NSOperationQueue currentQueue]
// completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
// UIImage *imageMain = [UIImage imageWithData:data];
// self.imageTest = [[UIImage alloc] init];
// self.imageTest = [self imageWithImage:imageMain forRowAtIndexPath:indexPath];
// NSLog(#"%lx", (unsigned long)imageData.length);
// }];
//Synchronous handler
NSData * imageData = [[NSData alloc] initWithContentsOfURL:url];
self.imageTest = [UIImage imageWithData: imageData];
NSLog(#"%lx", (unsigned long)imageData.length);
}
2015-01-06 07:44:26.564 Huckleberry[12733:361944] i.imgur.com/EXtwoxT.jpg
2015-01-06 07:44:26.600 Huckleberry[12733:361944] 0
First off, your code is missing a protocol for the URL -- NSURL can handle different protocols and doesn't just default to http. Prefix http:// to your URL and see if that gets you some data.
Secondly, that URL isn't actually the URL of the image -- I believe that URL will return the whole HTML imgur page, which is most likely not what you want (since you're trying to create a UIImage with the data).
Instead, try looking into the Imgur API (https://api.imgur.com) -- there's even a link on that page to an example Obj-C library (https://github.com/geoffmacd/ImgurSession)
I'm very new to iOS programming, and am trying to figure out something that is probably trivial. I'm trying to fetch Json data from Flickr, specifically just images, and use this data to populate pictures on a UITableView. This is my attempt:
- (void)jsonParsing
{
//-- Make URL request with server
NSHTTPURLResponse *response = nil;
NSString *jsonUrlString = [NSString stringWithFormat:#"http://api.flickr.com/services/feeds/photos_public.gne?tagmode=any&format=json&tags=QUERY"];
NSURL *url = [NSURL URLWithString:[jsonUrlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
//-- Get request and response though URL
NSURLRequest *request = [[NSURLRequest alloc]initWithURL:url];
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
//-- JSON Parsing
self.flickrArray = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:nil];
NSLog(#"Result = %#",self.flickrArray);
for (NSMutableDictionary *dic in self.flickrArray)
{
NSString *string = dic[#"media"];
if (string)
{
NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
dic[#"media"] = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
}
else
{
NSLog(#"Error in url response");
}
}
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// Return the number of rows in the section.
return [self.flickrArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
NSData *imageData = [self.flickrArray objectAtIndex:indexPath.row];
cell.image = [UIImage imageWithData:imageData];
return cell;
}
The only thing happening in the NSLog is : Result = (null). I can't for the life of me figure out what I'm doing incorrectly.
hi i tried to display images from json to CollectionView .
my code is...
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://zoo.com/jh/image.php"]];
[request setHTTPMethod:#"GET"];
[request setValue:#"application/json;charset=UTF-8" forHTTPHeaderField:#"content-type"];
NSError *err;
NSURLResponse *response;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSDictionary *jsonArray = [NSJSONSerialization JSONObjectWithData:responseData options: NSJSONReadingMutableContainers error: &err];
NSArray *headlines=[jsonArray1 objectForKey:#"image_gallery"];
for (int i=0;i<[headlines count]; i++)
{
NSString *moblinks=[[headlines objectAtIndex:i]objectForKey:#"image_url"];
[self.itemshowdetailsAr objectAtIndex:moblinks];
NSLog(#"%#",moblinks);
}
and my result in console
2014-06-20 15:05:27.005 Collection[3945:60b] http://xxxxxx/jh/ju_image/gal_1.jpg
2014-06-20 15:05:27.007 Collection[3945:60b] http://xxxxxx/jh/ju_image/gal_2.jpg
2014-06-20 15:05:27.007 Collection[3945:60b] http://xxxxxx/jh/ju_image/gal_3.jpg
2014-06-20 15:05:27.007 Collection[3945:60b] http://xxxxxx/jh/ju_image/gal_4.jpg
2014-06-20 15:05:27.008 Collection[3945:60b] http://xxxxxx/jh/ju_image/gal_5.jpg
2014-06-20 15:05:27.008 Collection[3945:60b] http://xxxxxx/jh/ju_image/gal_6.jpg
my collectionview code
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
CollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:#"Cell" forIndexPath:indexPath];
NSString *ImageURL =[self.itemshowdetailsAr objectAtIndex:indexPath.row];
NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:ImageURL]];
cell.imageView.image = [UIImage imageWithData:imageData];
cell.imageView.userInteractionEnabled=YES;
cell.imageView.contentMode = UIViewContentModeScaleToFill;
// cell.imageView.tag=i-1;
return cell;
}
but i got empty Collection View only.where i made mistake?i got array of url in console but cell is not displaying images.
By the looks of it you're trying to download image on the main thread and I'm guessing that the UI might be freezing while network requests are processed. Instead load the images asynchronously and away from the main thread by doing something like
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
CollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:#"Cell" forIndexPath:indexPath];
NSURLSession *session=[NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[[session dataTaskWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:[self.itemshowdetailsAr objectAtIndex:indexPath.row]]] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
cell.imageView.image = [UIImage imageWithData:data];
cell.imageView.userInteractionEnabled=YES;
cell.imageView.contentMode = UIViewContentModeScaleToFill;
}];
}] resume];
return cell;
}
The NSURLSession task will run away from the main thread. The completion handler will be called when the imageData has been downloaded. At this point an operation is added to the main thread to update the imageView within your collectionViewCell.
I having a bit difficulty loading images from a json file into UIImage - Table Cells in Xcode. I tried to load the images from the server into a NSArray then populating the table view UIImage cells. Is there something that I am missing here?
Image are located on a SQL server.
Thanks for the help.
Here is the server output from the PHP into Xcode. (cover_image)
(
"13497074790148.jpeg",
"13494650900147.png",
"13494606630147.png",
"13494605220147.jpeg",
"13494602920147.jpeg",
"13494601850147.jpeg",
"13491916300147.jpeg"
)
Here is the code in Xcode
NSArray *itemsimages = [[NSArray alloc]initWithArray:[results valueForKeyPath:#"cover_image"]];
self.itemImages = itemsimages;
Here is the code in table cells
UIImage *imageitm = [UIImage imageNamed: [self.itemImages objectAtIndex: [indexPath row]]];
cell.itmImage.image = imageitm;
return cell;
You don't have those images stored locally so it doesn't have any images to display. I suggest using SDWebImage to provide asyncronous image loading from remote location + caching mechanism.
-(void) viewDidLoad
{
NSURL *url = [NSURL URLWithString:#"YOUR URL"];
NSData *data = [NSData dataWithContentsOfURL:url];
NSError *error;
NSMutableDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSMutableArray *img = [[NSMutableArray alloc]init];
NSArray *websiteDetails = (NSArray *) [json objectForKey:#"logos"];
for(int count=0; count<[websiteDetails count]; count++)
{
NSDictionary *websiteInfo = (NSDictionary *) [websiteDetails objectAtIndex:count];
imagefile = (NSString *) [websiteInfo objectForKey:#"image_file"];
if([imagefile length]>0)
{
NSLog(#"Imagefile URL is: %#",imagefile);
[img addObject:imagefile];
}
}
//NSarray listofURL
listofURL = img;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = #"SimpleTableItem";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
dispatch_queue_t concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
//this will start the image loading in bg
dispatch_async(concurrentQueue, ^{
NSURL *url = [NSURL URLWithString:[listofURL objectAtIndex:indexPath.row]];
NSData *image = [[NSData alloc] initWithContentsOfURL:url];
//this will set the image when loading is finished
dispatch_async(dispatch_get_main_queue(), ^{
cell.imageView.image = [UIImage imageWithData:image];
});
});
}
return cell;
}
You need to have a proper url in json response or you can store the common part of the url in the code itself and append it later with the image name returned from server.
I did as follows in the same condition
__autoreleasing NSError* error = nil;
id result = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSDictionary *dict = ((NSDictionary *) result)[#"result"];
NSString *url = dict[#"imageURL"];
NSData *imageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:url]];
UIImage *image = [[UIImage alloc] initWithData:imageData];
[_buttonImageView setImage:image forState:UIControlStateNormal];
where data is the response returned from server.