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

标签 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

最佳答案

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

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

对于Xcode 4,点击主工程,点击Build Phases,可以看到Compile SourcesCopy Bundle Resources,详细步骤如下-

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

关于javascript - 如何在 iOS 中获取 js 文件路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9565327/

相关文章:

objective-c - 获取设置的纪元时间与现在的秒数之间的差异

ios - 在后台创建的 NSManagedObject 在主线程上变成错误

向下滚动时 JavaScript 菜单隐藏,停止时出现

android - PhoneGap : diagnostic plugin is not working in iphone

iphone - 如何更改铃声模式(静音或振动)

ios - AQGridView EXC_BAD_ACCESS _basicHitTest :withEvent:

ios - MarqueeLabel Swift 不工作

javascript - CouchDB + Datamapper + View = 无 ID

javascript - Angular 2+ window.onfocus 和 windows.onblur

javascript - 如何使用 var javascript onchange 事件更新输入类型 ="text"值?