UIWebView doesn't load external Javascript file

前端 未结 4 1345
臣服心动
臣服心动 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: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.

提交回复
热议问题