xcode 检查捆绑包中是否存在图像 - iPhone

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7931315/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 22:16:18  来源:igfitidea点击:

Checking if Image Exists in Bundle - iPhone

iphoneobjective-cxcodesdknsfilemanager

提问by GuybrushThreepwood

I have an app with a number of images. I want to check if an image exists in the bundle. If it does I display it, if not I display a replacement image.

我有一个包含许多图像的应用程序。我想检查捆绑包中是否存在图像。如果是我显示它,如果不是我显示一个替换图像。

The code below is what I've come up with, however it does not work. Can anyone spot what is wrong ?

下面的代码是我想出来的,但是它不起作用。任何人都可以发现有什么问题吗?

Thank you !

谢谢 !

NSString * photo = [NSString stringWithFormat:@"%d.jpg", UniqueID];    

NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:photo];
if([fileManager fileExistsAtPath:path])
{

    [image setImage:[UIImage imageNamed:photo]];  
}

else {

    NSLog(@"Hello");

    [image setImage:[UIImage imageNamed:@"iPhoneHD.png"]];

}

EDIT - Changed following Simon's post below, however still not working correctly. Else statement always triggers.

编辑 - 按照下面的西蒙的帖子进行了更改,但仍然无法正常工作。Else 语句总是触发。

回答by Robin Summerhill

You are looking in your App's Documents directory. Is this really where you are expecting to find the images? If they are actually resources added to your bundle then you need to do this:

您正在查看应用程序的文档目录。这真的是您期望找到图像的地方吗?如果它们实际上是添加到您的包中的资源,那么您需要执行以下操作:

NSString *path = [[NSBundle mainBundle] pathForResource:uniqueID ofType:@"jpg"];

Easier still - just try loading the named image. If it fails then load the default:

更简单 - 只需尝试加载命名图像。如果失败,则加载默认值:

UIImage *tempImage = [UIImage imageNamed:photo];

if (!tempImage) {
    tempImage = [UIImage imageNamed:@"iPhoneHD.jpg"]
}

[image setImage:tempImage];

回答by Kursat Turkay

+(BOOL) fileExistsInProject:(NSString *)fileName
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *fileInResourcesFolder = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:fileName];
    return [fileManager fileExistsAtPath:fileInResourcesFolder];
}

is my answer.

是我的答案。



如果文件存在于包中,则返回 YES。您不必对路径做任何事情。就说 [fileExistsInProject:@"blabla.ext"]

回答by Simon Lee

You have the if statement the wrong way, you are saying if it DOESN'T exist, then use it, otherwise use the default one.....you want...

你有错误的 if 语句,你是说如果它不存在,那么使用它,否则使用默认的......你想要......

if([fileManager fileExistsAtPath:path])