我将一个.js文件拖放到我的项目中。我想加载它,但它不工作。它给了我一个空路径。如何在iOS中获取js文件路径?
这是我第一次尝试获取路径
NSString *path = [[NSBundle mainBundle] pathForResource:@"SearchWebView" ofType:@"js"];
这是行不通的。于是我想我可能需要将其复制的文件/
于是我运行复制文件
- (NSString *)getJSFilePath {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
return [documentsDir stringByAppendingPathComponent:@"SearchWebView.js"];
}
- (void) copyJSFileIfNeeded{
//Using NSFileManager we can perform many file system operations.
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSString *jsPath = [self getJSFilePath];
BOOL success = [fileManager fileExistsAtPath:jsPath];
if(!success) {
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"SearchWebView.js"];
success = [fileManager copyItemAtPath:defaultDBPath toPath:jsPath error:&error];
if (!success){
//NSAssert1(0, @"Failed to create writable database file with message '%@'.", [error localizedDescription]);
}
}
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
[self performSelector:@selector(copyJSFileIfNeeded)];
}
它不创造我的文档文件夹中的新副本文件。我不知道为什么? 我可以使用相同的方法来复制plist或sqlite文件,但“.js文件”没有响应。 我也检查文件是否在我的项目包中。
+0
删除“SearchWebView.js”,并再次将文件拖动到您的项目,并检查“拷贝文件到目标文件夹”选项。 –
2012-03-05 10:57:21
+0
如果'!success'试图复制文件? –
2012-03-05 10:57:40
+0
@Vince,因为我不知道为什么我不能在主包中获得文件... –
2012-03-06 01:27:28