代码之家  ›  专栏  ›  技术社区  ›  Amarsh

UIWebView不加载外部Javascript文件

  •  26
  • Amarsh  · 技术社区  · 14 年前

    code.js 文件。如果我在HTML页面中复制/粘贴文件的内容,效果会很好。两者 index.html 文件在同一目录中。这是代码片段。任何帮助都会很好。

    索引.html:

    <html>
    <head>
    <script type="text/javascript" src="code.js"></script>
    </head> 
    <body onload="drawImage()">
      <div><canvas id="canvas" width="320" height="480"></canvas></div> 
    </body>
    </html>
    

    - (void)viewDidLoad {
      [super viewDidLoad];
    // load the first webpage
    [homePageWebView loadRequest:[NSURLRequest requestWithURL:[NSURLfileURLWithPath:
      [[NSBundle mainBundle] pathForResource:@"index"ofType:@"html"] isDirectory:NO]]];
    }
    
    4 回复  |  直到 13 年前
        1
  •  60
  •   Linda    14 年前

    在Xcode中打开项目。转到“目标”并查看“编译源代码”。如果您在该文件夹中看到您的js文件,请将其移动到“Copy Bundle Resources”文件夹,然后将其从“Compile Sources”文件夹中删除。

    如果已经安装该应用程序进行测试,请从iPhone中删除该应用程序。转到Xcode中的Build菜单并清除所有目标。然后重新编译。

    现在检查HTML文件是否真的看到了js文件。

    琳达

        2
  •  7
  •   Harry Wood    12 年前

    您需要将html文件读入字符串,并在加载时设置baseURL,以便可以理解相对路径。

    NSError* error;
    NSString* html = [NSString stringWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"] encoding:NSASCIIStringEncoding error:&error];
    
    [webview loadHTMLString:html baseURL:[self getBaseURL]];
    
    - (NSURL*) getBaseURL {
        NSString* path = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"];
        NSRange r = [path rangeOfString:@"/" options:NSBackwardsSearch];
        path = [path substringToIndex:r.location];
    
        path = [path stringByReplacingOccurrencesOfString:@"/" withString:@"//"];
        path = [path stringByReplacingOccurrencesOfString:@" " withString:@"%20"];
        path = [NSString stringWithFormat:@"file:/%@//",path];
        return  [NSURL URLWithString:path];
    }
    

        3
  •  6
  •   NSRover    12 年前

    为了补充琳达的回答,您可以在这里找到文件:

    enter image description here

        4
  •  5
  •   dda    13 年前

    我也面临同样的问题:我克服了这个问题,在向XCode添加文件时做了一件简单的事情,我做了一个小的更改,如下图所示:

    在下图中,一个用于添加类似HTML、Javascript和CSS的文件,另一个用于一般XCode文件。

    for HTML, Javascript and CSS files

    For general XCode files