user2545330
user2545330

Reputation: 408

UIImage imageWithContentsOfFile correct pathForResource

I have resources:

Test.png
test1.jpg
tesT2.jpg
tEst3.jpg

I need to show this image in UIImageView. So I wrote:

imgView.image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:[myObject.filename stringByDeletingPathExtension] ofType:[myObject.filename pathExtension]]];

myObject is entity in my model. I get filename from xml, but in xml it have format like:

filename="test.png"
filename="test1.jpg"
filename="test3.jpg"
filename="test3.jpg"

So my Image is (null) because in pathForResource I search @"test" ofType "png", but need @"Test" ofType"png".

How I can get correct resources without renaming them?

Upvotes: 3

Views: 728

Answers (4)

Hussain Shabbir
Hussain Shabbir

Reputation: 15015

How I can get correct resources without renaming them?

Basically iOS contains HFSX file system which is case sensitive. So without renaming the files it is not possible to get the correct resources. Refer this

Also the other alternative is, as @wain said, if you have file store in any directory, then you can just parse from that directory and then do a case insensitive filter to get the matching name and use that for fetching the exact filename from directory and then pass intopathForResourceofNSBundleapi. Refer this for getting the list of file names from directory

Upvotes: 1

monK_
monK_

Reputation: 397

You should get the list of files in your bundle with the appropriate extension with

NSArray *files = [[NSBundle mainBundle] pathsForResourcesOfType:[myObject.filename pathExtension] inDirectory:nil];

Now you go through the array files and try to match your filename. This is done using NSArray's method - (NSArray *)filteredArrayUsingPredicate:(NSPredicate *)predicate (clean way) or by looping through the array (old school way).

Predicates are described in the Predicate Programming Guide.

For the old school method, simply loop like this:

for (String *file in files)
{
    if ([file caseInsensitiveCompare:myObject.filename] == NSOrderedSame) 
    {
        // do whatever you need to do with the file

        break; // stop the loop
    }
}

Upvotes: 1

sage444
sage444

Reputation: 5684

You can get all resources from bundle see answers here Count of images in my NSBundle mainBundle bundlePath and manually check names of image that need to load

Upvotes: 1

Wain
Wain

Reputation: 119031

If you can't rename the source data (which you should do really), then you would need to use the file manager to get a list of all of the files available and then do a case insensitive filter to get the matching name and use that.

Upvotes: 5

Related Questions