2011-05-04 91 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

添加@馬丁威克曼的泛化(與回退),一切都應該是巨大的。