UIWebView doesn't load external Javascript file

前端 未结 4 1330
臣服心动
臣服心动 2020-12-04 15:03

I have the following innocent-looking code (index.html), but it doesn\'t load the code.js file. It works well if I copy/paste the contents of the file in the HT

相关标签:
4条回答
  • 2020-12-04 15:12

    To supplement Linda's Answer here is where you find the files:

    enter image description here

    0 讨论(0)
  • 2020-12-04 15:17

    I also faced the same problem: I overcame it by doing the simple thing when adding the files to XCode I did a small change that is shown in the figure below:

    In the figure below, one is for adding HTML, Javascript and CSS like files and the second is for general XCode files.

    for HTML, Javascript and CSS files

    For general XCode files

    0 讨论(0)
  • 2020-12-04 15:20

    You need to read the html file into a string and set the baseURL when loading so relative paths can be understood.

    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];
    }
    

    Something like that should work for you.

    0 讨论(0)
  • 2020-12-04 15:22

    I have found that Xcode thinks that the js file needs to be compiled.

    Open the project in Xcode. Go to "Targets" and look in "Compile Sources". If you see your js file in that folder, move it to the "Copy Bundle Resources" folder and delete it from the "Compile Sources" folder.

    Delete the app from your iPhone if it is installed already for testing. Go to the Build menu in Xcode and Clean all Targets. Then recompile.

    Check now to see if your HTML file actually sees your js file now.

    Linda

    0 讨论(0)
提交回复
热议问题