如何在iOS中获取js文件路径?

时间:2012-03-05 10:48:38

标签: javascript iphone objective-c ios copy

我将.js文件拖放到我的项目中。我想加载它,但它不起作用。它给了我一条空路径。

这是我第一次尝试获取路径

NSString *path = [[NSBundle mainBundle] pathForResource:@"SearchWebView" ofType:@"js"];

这不起作用。那么我想我可能需要在Documents /

中复制它

所以我运行了复制文件

- (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文件”没有响应。 我还检查文件是否完全在我的项目包中。

enter image description here

1 个答案:

答案 0 :(得分:13)

当您添加JavaScript文件时,Xcode会检测到该文件是源代码文件,假设您要编译它并自动将其添加到编译源构建阶段。

要阻止Xcode尝试编译它并使其复制文件,请在“组和文件”列表中展开目标,从编译源构建阶段中删除JavaScript文件并将其添加到复制捆绑资源构建阶段。

对于Xcode 4,单击主项目,单击Build Phases,您将找到编译源复制包资源,详细步骤如下 -

  1. Project Navigator(Cmd + 1)
  2. 选择您的项目
  3. 选择目标
  4. 选择“Build Phases”选项卡,您将获得您想要的部分。
  5. 添加所需的js文件以复制捆绑资源并从编译源中删除<​​/ li>