iOS Split view controller - changing image in detailViewController - ios

This is another of those "I'm sure there's an easy answer to this" questions, but I find myself baffled.
I'm using the split view controller from the template. I'm successfully passing a NSString to the _detailItem variable, but am unable to use it to create and load an image into an UIImageView (named "stripImage").
It works up until:
[self.stripImage setImage:[UIImage imageNamed: _detailItem]];
If I put a string literal into the same line of code (like #"image20.jpg"), it works fine.
- (void)configureView
{
// Update the user interface for the detail item.
if (self.detailItem) {
NSLog(#"_detailItem is still: %#",_detailItem);
// correctly reports the name of the imagefile (for example: "image20.jpg"
[self.stripImage setImage:[UIImage imageNamed: _detailItem]];
NSLog(#"The image being shown is: %#",self.stripImage.image);
//returns "The image being shown is: (null)"
}
}
Please help keep my head from exploding. Thanks in advance.
... and I've tried it this way:
(in my Master view controller):
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(#"Selected row %i",[indexPath row]);
NSString *imageName = [[stories objectAtIndex:[indexPath row]] objectForKey:#"link"];
NSLog(#"The image is: %#", imageName);
// These two work, oddly enough...
self.detailViewController.detailTitle.text = [[stories objectAtIndex:[indexPath row]]
objectForKey:#"title"];
self.detailViewController.detailSubtitle.text = [[stories objectAtIndex:[indexPath row]]
objectForKey:#"subtitle"];
// this one, not so much...
[self.detailViewController loadUpImageWith:imageName];
}
and in my Detail view controller:
- (void)loadUpImageWith:(NSString *)what
{
NSString *path = [[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:[NSString
stringWithFormat:#"strips/%#", what]];
NSLog(#"The file's url is: %#",path);
UIImage *img = [UIImage imageWithContentsOfFile:path];
NSLog(#"The resultant image is: %#",img);
stripImage.image = img;
}
But here's the weird thing... If I replace the variable ("what" in this case) with a string literal:
NSString *path = [[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:[NSString
stringWithFormat:#"strips/%#", #"grumbles300.jpg"]];
... it works, displaying that one image. But I want to be able to use a variable there!!
Help me Obiwan Kenobi! You're my only hope.

Embarrassing operator error.
I was adding a buncha images to the bundle, but it apparently kept track of the folder that contained them, which needed to be added to the file name. I thought UIImage imageNamed: would track down the images, as long as they were contained in the main bundle. Apparently not.
Perhaps this would be useful to someone who's experiencing the same sort of brain fart.
After resolving this, it was easy to do this:
- (void)loadupDetailTitle:(NSString *)title
subtitle:(NSString *)subtitle
image:(NSString *)imageName
{
NSString *path = [#"strips/" stringByAppendingPathComponent:imageName];
stripImage.image = [UIImage imageNamed:path];
detailTitle.text = title;
detailSubtitle.text = subtitle;
}

Related

Image not showing in my UICollectionView

So I've been looking for a solution to this issue, but can't seem to find anything. I have an array that I load with image paths using the below method
- (IBAction)btnPictures:(id)sender {
// Create the next view controller.
ImageGalleryViewController *galleryViewController = [[ImageGalleryViewController alloc] initWithNibName:#"ImageGalleryViewController" bundle:nil];
// Search for paths and get users home directory
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
// get path at first index (in case multiple returned
NSString *documentsDirectory = [paths objectAtIndex:0];
NSArray *dirContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsDirectory error:nil];
NSArray *files = [dirContents filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"pathExtension IN %#", #"png"]];
// Pass the selected object to the new view controller.
[galleryViewController setImageArray:files];
// Push the view controller.
[self.navigationController pushViewController:galleryViewController animated:YES];
}
That image array is then sent to the below method in my UICollectionViewController
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
ImageGalleryViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:#"ImageGalleryViewCell" forIndexPath:indexPath];
NSLog(#"Image at index %#", [imageArray objectAtIndex:indexPath.row]);
[cell.galleryImage setImage:[UIImage imageWithContentsOfFile:[imageArray objectAtIndex:indexPath.row]]];
[cell setBackgroundColor:[UIColor whiteColor]];
return cell;
}
I verified the objectAtIndex is returning a valid image name through my NSLog, but for some reason the cell is not displaying it.
Any help is greatly appreciated, thanks in advance.
The array returned by -contentsOfDirectoryAtPath: of NSFileManager doesn't provide the full file path but just the name of files and directories. You have to append each values in the array to the path to your Document Directory.
Something like this:
NSString *documentsDirectoryPath = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents"];
NSString *imagePath = [documentsDirectoryPath stringByAppendingPathComponent:[imageArray objectAtIndex:indexPath.row]];
UIImage *image = [UIImage imageWithContentsOfFile:imagePath];
I suspect, you are not initialising any cells before using (dequequing) one. Initialise your cell, and try again. Good Luck!
PS: by initialising I mean, alloc init your cell.

Why are characters and forward slashes being appended to my NSURL?

My images are not loading from their URLs. When I log the NSURL, it appears correct
my.website.com/images/image1.png
But when I set breakpoints, the NSURL shows up in the debugger console as
my.website.com/images/image1.png\x05\b
I have checked the json through my web browser, and it is perfectly valid. The string ends with the 'g' of "png".
I am using SDWebImage to asynchronously load images for my table cells. The URLs to be used for the pictures are coming from a php file that encodes the JSON.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
SpotsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"SpotCell" forIndexPath:indexPath];
NSInteger row = indexPath.row;
if (self.spotDictionary)
{
NSDictionary* spot = (NSDictionary*)[self.spotDictionary objectForKey:[NSString stringWithFormat:#"%d", row]];
NSString* title = [spot objectForKey:#"Title"];
NSURL* imageURL = [NSURL URLWithString:(NSString*)[spot objectForKey:#"Image"]]; NSLog(#"%#", imageURL);
UIImage* placeholder = [UIImage imageNamed:#"placeholder.png"];
// See ~*~ below
NSURL* testURL = [NSURL URLWithString:#"http://www.hdwallpaperspot.com/wp-content/uploads/2013/08/Volvo-station-wagon-612pb.jpg"];
cell.nameLabel.text = title;
[cell.pictureView setImageWithURL:imageURL
placeholderImage:placeholder]; // SDWebImage category for UIImage
//breakpoint here
}
return cell;
}
~*~
To make sure SDWebImage was performing correctly, I grabbed an image off the net to temporarily test the library, and it performed wonderfully. I have checked the class of the "Image" object and it is _NSCFString. The (NSString*) cast was added in case my understanding of the interchangeability between NSCFString and NSString is flawed. No luck.
This is very embarrassing, but I'll share my mistake so no one gets misconcepted.
I forgot to specify the protocol (http://) in my Image JSON object.
I figured NSURL class would have some sort of default HTTP checking, but I realize that's not feasible, as there are other protocols that could be used with an NSURL.
Thanks #rmaddy for pointing out the debugger, uhm, bug.

Load images from a documents subdirectory into UICollectionViewCell

I have several images in png format in "/Documents/saved/" directory.
I loaded this directory into an array called "contents"
When i use NSLog to view the contents of this array, i see the images as well as a .DS_STORE file
What i want to do is load all these images into UICollectionView cells.
I tried this,
[[cell collectionImageView] setImage:
[UIImage imageWithContentsOfFile:
[contents objectAtIndex:indexPath.item]]];
The collectionImageView is connected to the UIImageView in the UICollectionViewCell
But it doesn't seem to work.EDIT
NSString *dataPath = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents/DImage"];
NSArray *contents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:dataPath error:NULL];
NSLog(#"%#", contents);
This gives me the output
2013-03-25 10:37:20.186 aUX[543:c07] (
".DS_Store",
"savedImage_0.png",
"savedImage_1.png",
"savedImage_2.png",
"savedImage_3.png",
"savedImage_4.png",
"savedImage_5.png"
)
(I have dragged a UIImageView named collectionImageView.)
I need to display these images one by one in the collection view cells.
It is not clear what data types you are using. Maybe breaking up your one-liner might help bring more clarity to the situation. Also, in this way you can check each step with NSLog or in the debugger.
NSString *fileName = [contents objectAtIndex:indexPath.item];
NSString *path = [filesDirectory stringByAppendingPathComponent:fileName];
UIImage *image = [UIImage imageWithContentsOfFile:path];
UIImageView *cellImageView = cell.collectionImageView;
cellImageView.image = image;
Maybe your contents array contains NSURLs rather than NSStrings. In this way you can find out.
in ur cellForRowAtIndexPath
cell.collectionImage.image=[contents objectAtIndex:indexPath.row];
return cell;

How to get file extension (compare)

i´m parsing the filedirectory from dropbox into a mutablearray, to show it in a table view.
how can i compare the file extension? (.doc, or .jpg,....)
if ([[NSString stringWithFormat:#"%#",[test objectAtIndex:indexPath.row]] isEqualToString:#"??????"] ) {
[cell.extensionView setImage:[UIImage imageNamed:#"word.png"]];
}
isEqualToWhat? is it possible to use wildcards?
Don't use stringWithFormat unless you actually have a format. Your code would be much cleaner if you did something like this:
NSString *filename = [text objectAtIndex:indexPath.row];
NSString *ext = [filename pathExtension];
if ([ext isEqualToString:#"doc"]) {
[cell.extensionView setImage:[UIImage imageNamed:#"word.png"]];
} else if ([ext isEqualToString:#".jpg"]) {
[cell.extensionView setImage:[UIImage imageNamed:#"jpeg.png"]];
}
There is a better way than setting up this big if-else block. I imagine you have lots of different extensions you wish to check. Setup a dictionary with the extensions and images. Something like:
NSDictionary *extensionThumbnails = #{
#"doc" : [UIImage imageNamed:#"word.png"],
#"xls" : [UIImage imageNamed:#"excel.png"],
#"jpg" : [UIImage imageNamed:#"jpeg.png"]
};
Add an entry for each extension and image you have. Then your original code (now using modern Objective-C syntax) becomes:
NSString *filename = text[indexPath.row];
NSString *ext = [filename pathExtension];
UIImage *thumbnail = extensionThumbnails[ext];
if (!thumbnail) {
thumbnail = [UIImage imageNamed:#"unknown.png"];
}
[cell.extensionView setImage:thumbnail];

How to separate images out from Resources in iOS

I'm displaying a set of images in my app. I've got the code working when I load the image from the Resources folder, like so:
- (void)viewDidLoad
{
NSMutableArray *array = [[NSMutableArray alloc] init];
[array addObject:[NSString stringWithFormat: #"pic_a"]];
[array addObject:[NSString stringWithFormat: #"pic_b"]];
[array addObject:[NSString stringWithFormat: #"pic_c"]];
[array addObject:[NSString stringWithFormat: #"pic_d"]];
int index = arc4random() % [array count];
NSString *pictureName = [array objectAtIndex:index];
NSString* imagePath = [ [ NSBundle mainBundle] pathForResource:pictureName ofType:#"png"];
UIImage *img = [ UIImage imageWithContentsOfFile: imagePath];
if (img != nil) { // Image was loaded successfully.
[imageView setImage:img];
[imageView setUserInteractionEnabled:NO];
[img release]; // Release the image now that we have a UIImageView that contains it.
}
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
}
However, if I create an "images" group within the "Resources" group, and put try to load the images from there, the image within the view shows up blank.
[array addObject:[NSString stringWithFormat: #"images/pic_a"]];
[array addObject:[NSString stringWithFormat: #"images/pic_b"]];
[array addObject:[NSString stringWithFormat: #"images/pic_c"]];
[array addObject:[NSString stringWithFormat: #"images/pic_d"]];
I'd like to separate the images out from the nib files and all the other cruft. What's the best way to do that?
Even if you have the images in a separate group within Resources, you can load them by calling the name, e.g. use this one line
UIImage *img = [UIImage imageNamed:[array objectAtIndex:index]];
in place of these three lines:
NSString *pictureName = [array objectAtIndex:index];
NSString* imagePath = [ [ NSBundle mainBundle] pathForResource:pictureName ofType:#"png"];
UIImage *img = [ UIImage imageWithContentsOfFile: imagePath];
You will still fill the array simply by
[array addObject:[NSString stringWithFormat: #"pic_a"]];
If you have both jpg and png files, then you should append .png to the end of the file names. Otherwise, leaving it off is fine.
Try using the imageNamed: method instead of imageWithContentsOfFile:
You need to create a physical folder called images (it should have a blue color instead of the usual yellow color)
Remember that adding groups inside your project it is simply for organization and look within Xcode. You adding a group will not change the fact that the images will be saved in the main bundle. If you are trying to find them using the images group in the string it will not find them.
There are some things you can do to make this work, but in reality you don't need to.

Resources