2011-05-04 54 views
5

我需要分发所在目录的HTML文件和图片与我的应用程序。如何查找本地化目录的路径?

的应用有不同的语言支持。我创建了一个目录为每一种语言,然后从中挑选基于当前的区域设置是正确的:

NSString *language = [[NSLocale preferredLanguages] objectAtIndex:0]; 
NSString *path = [[NSBundle mainBundle] pathForResource:@"index" 
               ofType:@"html" 
              inDirectory:[language stringByAppendingPathExtension:@"html"];]; 

if (![[NSFileManager defaultManager] fileExistsAtPath:path]) 
{ 
    // Fallback to english 
    path = [[NSBundle mainBundle] pathForResource:@"index" 
              ofType:@"html" 
             inDirectory:@"en.html"]; 
} 

我怎样才能更好地处理这个,而不必做以上(这是一个有点乱) ?

我想也许使用xx.lproj目录这个不知何故,并把本地化HTML 目录每个xx.lproj目录,并使用NSBundle pathForResource找到正确的文件。尽管如此,仍然无法实现。

回答

0

您可以使用此:

NSString *filename = [NSString stringWithFormat:@"html_%@.html", NSLocalizedString(@"abbr", @"")]; 
+0

算不上什么我要找的。 – 2011-05-04 09:43:54

4

使用xx.lproj文件夹与[NSBundle pathForResource:ofType:]是直线前进。

您可以添加index.html到Xcode的项目文件,然后让它从它的“获取信息”窗口本地化。添加像“德”另一种语言,和Xcode中会复制index.html到新创建的de.lproj。如果您删除该文件,该应用程序将回退到英文版。

您可以记录测试:

NSLog([[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"]); 
+0

我很惊讶这不是被投票。如果你使用一个NSBundle的路径和URL的方法,很多搞清楚你的​​语言环境和区域文件夹的辛勤工作会自动为你完成。 – mahboudz 2014-06-07 08:36:26

+0

因为它在XCode 6.3.2中不起作用。不幸的是,总是返回零。 – 2015-06-15 13:40:58

3

我也是无法得到这个工作:

NSLog([[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"]); 

但这并使用标准的Xcode language.lproj结构(例如, en.lproj):

NSString *language = [[NSLocale preferredLanguages] objectAtIndex:0]; 
    NSString *htmlPath = [[NSBundle mainBundle] pathForResource:@"index" 
        ofType:@"html" 
        inDirectory:[language stringByAppendingPathExtension:@"lproj"]]; 

也删除额外;在上面马丁的原始问题中...

3

额外提示:确保您删除了构建产品中文件的非本地化版本,否则pathForResource将查找这些文件而不是本地文件。

1

为什么不forLocalization方式:

 htmlFile = [[NSBundle mainBundle] pathForResource:@"myContent" 
               ofType:@"html" 
              inDirectory:@"de.lproj" 
             forLocalization:@"de"]; 

在这里,这工作正常的Xcode 5.1.1和iOS 7.1

添加@马丁威克曼的泛化(与回退),一切都应该是巨大的。