Why is NSFileManager unable to find these png files? - ios

I have written code to open image files after studying answers to the questions found here (a, b, c, d, e, f & g). But NSFileManager is unable to find them even though I added the png files to the project. I'm reasonably confident my code should be able to recognise either of the png files if they were in the right directory.
e.g.
- (void)viewDidLoad {
[super viewDidLoad];
NSFileManager *fileManager = [[NSFileManager alloc] init];
NSArray *dirPaths;
NSString *docsDir;
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = [dirPaths objectAtIndex:0];
NSLog(#"\ndirPaths %# \n\ndocsDir \n%#", dirPaths, docsDir);
NSString *imageFilePath = [docsDir stringByAppendingPathComponent:#"iTunesArtwork1024.png"];
NSLog(#"\n\nfile path should be \n\n%# \n\n", imageFilePath);
NSData *imageData = [NSData dataWithContentsOfFile:imageFilePath];
if ([fileManager fileExistsAtPath:imageFilePath])
{
NSLog(#"\nFound file path : %#", imageFilePath);
}
else
{
NSLog(#"\nImage file not found");
}
UIImage *image = [UIImage imageWithData:imageData];
UIImageView *logo = [[UIImageView alloc] init];
logo.image = image;
[self.view addSubview:logo];
}
But here is the log in the debug window
2017-07-14 18:26:35.679 IconShape[1089:348564]
dirPaths (
"/Users/gs/Library/Developer/CoreSimulator/Devices/57279C80-0937-4658-B0E6-7984B3768D56/data/Containers/Data/Application/18235DBF-7ADB-47D4-AFF9-282D02F2A0F8/Documents"
)
docsDir
/Users/gs/Library/Developer/CoreSimulator/Devices/57279C80-0937-4658-B0E6-7984B3768D56/data/Containers/Data/Application/18235DBF-7ADB-47D4-AFF9-282D02F2A0F8/Documents
2017-07-14 18:26:35.679 IconShape[1089:348564]
file path should be
/Users/gs/Library/Developer/CoreSimulator/Devices/57279C80-0937-4658-B0E6-7984B3768D56/data/Containers/Data/Application/18235DBF-7ADB-47D4-AFF9-282D02F2A0F8/Documents/iTunesArtwork1024.png
2017-07-14 18:26:35.679 IconShape[1089:348564]
Image file not found
Here is the state of the project after two png files were added.
Yet the log shows they are not visible to NSFileManager. So where would they be found ? i.e. what changes do I need to make to my code in order to find them ?
EDIT
This draft finds the png file following Subramanian's recommendation.
- (void)viewDidLoad {
[super viewDidLoad];
NSFileManager *fileManager = [[NSFileManager alloc] init];
NSString *imageFilePath = [[NSBundle mainBundle]pathForResource:#"iTunesArtwork1024" ofType:#"png"];
if ([fileManager fileExistsAtPath:imageFilePath])
{
NSLog(#"\nFound file path : %#", imageFilePath);
}
else
{
NSLog(#"\nImage file not found");
}
UIImage *image = [UIImage imageNamed:#"iTunesArtwork1024.png"];
UIImageView *logo = [[UIImageView alloc] initWithFrame:CGRectMake(100, 100, 50, 50)];
logo.image = image;
[self.view addSubview:logo];
}
The log now reads
Found file path : … .app/iTunesArtwork1024.png
and the image also appears in the subview.
__

Image is not in theDocument Directory, It's inside the bundle.
You have added the image files inside the project. But You are checking the image on Document Directory, Which is wrong. Image is inside app bundle.
You can simply assign the Image to UIImageView by the name of the image.
UIImage *image = [UIImage imageNamed:#"iTunesArtwork1024.png"];
UIImageView *logo = [[UIImageView alloc] init];
logo.image = image;
If you want to get the path of the image, then you have to use [NSBundle mainBundle]
[[NSBundle mainBundle]pathForResource:#"iTunesArtwork1024" ofType:#"png"];

You can access images with names which are added in projects. Try with below code
UIImage *image = [UIImage imageNamed:#"iTunesArtwork1024.png"];

The path where your are looking for the image is inside your device (real or simulator).
To load an image that is stored in your XCode project just do:
UIImage* image = [UIImage imageNamed:#"iTunesArtwork1024.png"];

Related

iOS Objective-C Display PNG Image In Custom Framework

I'm creating a custom framework. Previously in the framework we would download an image and use that to display in a button:
NSString *path = [NSString stringWithFormat: #"https://s3.amazonaws.com/assets/home.png"];
NSURL *url = [NSURL URLWithString:path];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *homeButton = [[UIImage alloc] initWithData:data];
self.rewardsCenterButton = [[UIBarButtonItem alloc] initWithImage:[homeButton imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]
style:UIBarButtonItemStylePlain
target:self
action: #selector(backToRewardsCenter:)];
However, in reviewing this we determined that this isn't good to have as a synchronous call so I'd like to add this PNG to the framework itself.
I've been able to do this by adding the image and ensuring it's included in the copy bundle resources Build Phase. With this set the image gets added in the universal framework output:
However, when I attempt to add this in code, it doesn't seem to show up. Also, when I add the framework in a project, I don't see the image being included, just the headers:
Here's what I've tried so far:
NSString* path = [NSString stringWithFormat:#"%#/TheoremReachSDK.framework/home.png", [[NSBundle mainBundle] bundlePath]];
UIImage *homeButton = [[UIImage alloc] initWithContentsOfFile:path];
And:
NSBundle *bundle = [NSBundle bundleForClass:[TheoremReach class]];
NSString *path = [bundle pathForResource:#"home" ofType:#"png"];
UIImage *homeButton = [[UIImage alloc] initWithContentsOfFile:path];
And:
UIImage *homeButton = [UIImage imageNamed:#"home.png"];
But none of those display anything. Any idea what I need to do to get the image to display?
I'm guessing NSBundle isn't finding the framework via the call to:
[NSBundle bundleForClass:[TheoremReach class]]
Try giving your framework an explicit bundle ID, e.g.: com.theoremreach.sdk, clean your projects and then rebuild.
You can then use code like this to fetch and display your image:
NSString *bundleIdentifier = #"com.theoremreach.sdk";
NSBundle *bundle = [NSBundle bundleWithIdentifier:bundleIdentifier];
if(bundle != nil) {
NSString *path = [bundle pathForResource:#"home" ofType:#"png"];
UIImage *homeButtonImage = [[UIImage alloc] initWithContentsOfFile:path];
if(homeButtonImage != nil) {
self.rewardsCenterButton = [[UIBarButtonItem alloc] initWithImage:[homeButtonImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]
style:UIBarButtonItemStylePlain
target:self
action: #selector(backToRewardsCenter:)];
} else {
NSLog(#"couldn't find home button image in bundle");
}
} else {
NSLog(#"could not find bundle with identifier %#", bundleIdentifier);
}

how to load image to uiimageview

how to load image to uiimageview from a custom folder
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
NSString*ext= [NSString stringWithFormat:#"/Imagenes/30775.png"];
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:ext];
//option 1
UIImage * myImage = [UIImage imageWithContentsOfFile: dataPath];
_img.image = myImage
///option 2
UIImageView * myImageView = [[UIImageView alloc] initWithImage: myImage];
_img = myImageView;
///option 3
NSData *imgData = [[NSData alloc] initWithContentsOfURL:[NSURL fileURLWithPath:dataPath]];
_img.image = [UIImage imageWithData:imgData];
i try 3 options but not working
any idea ?
the image is loading from a custom folder
i checked the path and is correct but not load
Your path #"/Imagenes/30775.png" seems to be wrong. Double check it. Otherwise following should work
UIImage * myImage = [UIImage imageWithContentsOfFile: dataPath];
_img.image = myImage
NSString*ext= [NSString stringWithFormat:#"/Imagenes/30775.png"];
Your path is wrong.I guess the Imagenes is a group in your project. So xcode is not create a folder in your project main folder. The groups is only helps you to view the files easily in the xcode program.
Also you don't need stringWithFormat.
Try this;
NSString*ext= #"30775.png";

ios load an image from docDir into UIimagview - viewDidLoad

I have a group of images saved in my DOcuments folder of the app. I got it to save to that location, I am having trouble loading from that location.
I got the UIimageView working hardcoded with images I dragged to a folder in the project with the code below in the viewDidLoad() method and when i ran the simulator it appeared.
UIImageView *bottomPic = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"pants.png"]];
bottomPic.frame = CGRectMake(65, 279, 200, 250);
[self.view addSubview:bottomPic];
[bottomPic release];
However when I want to load the image from the Documents Directory nothing loads - Am confused and couldn't find any exact information to help me out on this situation.. This is currently what I have and when I run it doesn't throw any errors but no image appears. Am I missing something in my code? (I'm new to objective-c!)
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"bottom1A2A6520-F556-436F-A1BC-D430223DC890-33098-00014708AE7E370F.png"]];
UIImage *image = [UIImage imageWithContentsOfFile:path];
UIImageView *bottomPic = [[UIImageView alloc] initWithImage:[UIImage imageNamed:path]];
bottomPic.frame = CGRectMake(65, 279, 200, 250);
[bottomPic setImage:image];
[self.view addSubview:bottomPic];
[bottomPic release];
A path is a path and an image is an image.
UIImage *image = [UIImage imageWithContentsOfFile:path];
UIImageView *bottomPic = [[UIImageView alloc] initWithImage:image];
Your code has a few issues. Try this:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = paths[0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"bottom1A2A6520-F556-436F-A1BC-D430223DC890-33098-00014708AE7E370F.png"];
UIImage *image = [UIImage imageWithContentsOfFile:path];
UIImageView *bottomPic = [[UIImageView alloc] initWithImage:image];
bottomPic.frame = CGRectMake(65, 279, 200, 250);
[self.view addSubview:bottomPic];
[bottomPic release];
Unrelated to the problem, you were needlessly using stringWithFormat:.
The real problem was creating the UIImageView with an unneeded image using imageNamed:.
If this doesn't work then verify that path actually represents a file that really exists in the Documents folder. Verify image isn't nil.
Also consider use ARC (automatic reference counting) to make your life a lot easier.
Update: It appears you needed NSDocumentDirectory instead of NSDocumentationDirectory.

Resizing an image from UIImagePickerController not working

I am following this post on how to resize an image. I placed the + (UIImage*)imageWithImage:(UIImage*)image scaledToSize:(CGSize)newSize; in selectExerciseImageViewController.h and copied the relevant code to selectExerciseImageViewController.m.
Then I attempt to resize the image, save it, and retrieve the saved image file into a UIImageView. but for some reason the image is never showing the the UIImageView and the last NSLog returns null
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
[picker dismissModalViewControllerAnimated:YES];
UIImage* newImage = [selectExerciseImageViewController imageWithImage:[info objectForKey:#"UIImagePickerControllerOriginalImage"]
scaledToSizeWithSameAspectRatio:CGSizeMake(40.0,40.0)];
NSData* imageData = UIImagePNGRepresentation(newImage);
// Give a name to the file
NSString* imageName = #"MyImage.png";
// Now, we have to find the documents directory so we can save it
// Note that you might want to save it elsewhere, like the cache directory,
// or something similar.
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* documentsDirectory = [paths objectAtIndex:0];
// Now we get the full path to the file
NSString* fullPathToFile = [documentsDirectory stringByAppendingPathComponent:imageName];
// and then we write it out
[imageData writeToFile:fullPathToFile atomically:NO];
//imageView.image = [info objectForKey:#"UIImagePickerControllerOriginalImage"];
_testimg.image = [UIImage imageNamed:#"MyImage.png"];
NSLog(#"asd %#",[UIImage imageNamed:#"MyImage.png"]);
}
[UIImage imageNamed:#"MyImage.png"];
This loads an image from the main application bundle. You are writing the file to the documents directory. You need to instantiate the UIImage object with a different method. Try:
[UIImage imageWithContentsOfFile:fullPathToFile];

iOS - Can't Display Downloaded Image

I am downloaded images using the below code, but whenever I try to display them nothing shows up. I have tested the downloading of the images to my desktop from the app (in simulator) and all the images are created just fine. So I know they are being saved into the App's Documents directory.
Any ideas on what I am doing wrong?
Download Image Code:
-(void)saveThumbnails:(NSMutableArray *)thumbnails{
for(NSNumber *videoID in thumbnails){
// Get an image from the URL below
NSURL *thumbnailURL = [self generateThumbnailURL:[videoID intValue]];
UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:thumbnailURL]];
NSLog(#"%f,%f",image.size.width,image.size.height);
// Let's save the file into Document folder.
// You can also change this to your desktop for testing. (e.g. /Users/kiichi/Desktop/)
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);//Find Application's Document Directory
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:#"DownloadedThumbnails"];
// NSString *dataPath = #"/Users/macminidemo/Desktop/gt";//DEBUG SAVING IMAGE BY SAVING TO DESKTOP FOLDER
//Check if Sub-directory exists, if not, try to create it
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath]){
NSError* error;
if([[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error]){
NSLog(#"New Folder Created!");
}
else
{
NSLog(#"[%#] ERROR: attempting to write create new directory", [self class]);
NSAssert( FALSE, #"Failed to create directory maybe out of disk space?");
}
}
NSArray *splitFilename = [[self generateThumbnailFilename:[videoID intValue]] componentsSeparatedByString:#"."];//Break Filename Extension Off (not always PNGs)
NSString *subString = [splitFilename objectAtIndex:0];
NSString *formattedFilename = [NSString stringWithFormat:#"%#~ipad.png",subString];
NSString *localFilePath = [dataPath stringByAppendingPathComponent:formattedFilename];
NSData *imageData = [NSData dataWithData:UIImagePNGRepresentation(image)];
[imageData writeToFile:localFilePath atomically:YES];
NSLog(#"Image: %# Saved!",formattedFilename);
}
}
Display Image Code:
if(currentVideo.thumbnail!=(id)[NSNull null] || ![currentVideo.thumbnail isEqualToString:#"missing_image.png"]){
NSArray *splitFilename = [currentVideo.thumbnail componentsSeparatedByString:#"."];//Break Filename Extension Off (not always PNGs)
NSString *subString = [splitFilename objectAtIndex:0];
NSString *formattedFilename = [NSString stringWithFormat:#"%#~ipad.png",subString];
UIImage *thumbnailImage = [UIImage imageNamed:formattedFilename];
NSLog(#"Image Name: %#",formattedFilename);
[videoThumbnail setImage:thumbnailImage];
[buttonVideo addSubview:videoThumbnail];
}else{
UIImage *thumbnailImage = [UIImage imageNamed:#"video-details-thumbnail"];
[videoThumbnail setImage:thumbnailImage];
[buttonVideo addSubview:videoThumbnail];
}
*And there are no issues displaying the buttonVideo or anything like that. I have tested just setting a test image and that one display just fine (i.e. the "else" statement when run individually works just fine using the default thumbnail)
The documentation for imageNamed says that it works with files that are in the app's main bundle. This suggests to me that it's only appropriate for images that are supplied as in-app resources. Try imageWithContentsOfFile: to get at the content of the documents directory.

Resources