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

Web*_*Lai 1 javascript iphone copy objective-c ios

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

这是我第一次尝试获得这条路

NSString *path = [[NSBundle mainBundle] pathForResource:@"SearchWebView" ofType:@"js"];
Run Code Online (Sandbox Code Playgroud)

这不起作用.那么我想我可能需要在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)];

}
Run Code Online (Sandbox Code Playgroud)

它不是在我的文档文件夹中创建新的副本文件.我不知道为什么?我可以使用相同的方法来复制plist或sqlite文件,但".js文件"没有响应.我还检查文件是否完全在我的项目包中.

在此输入图像描述

Sri*_*aju 13

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

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

对于Xcode 4,单击主项目,单击Build Phases,您将找到Compile SourcesCopy Bundle Resources,详细步骤如下 -

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