简体   繁体   English

在UIWebView中加载JavaScript文件

[英]Load a javascript file in a UIWebView

How do I load a UIWebView and then request a javascript file from my server and load that into the UIWebView ? 如何加载UIWebView ,然后从服务器请求JavaScript文件并将其加载到UIWebView

Say a problem occurs with the js code and I update it, you can refresh the app so that it sends a new request for the javascript file and you'll have the new version. 假设js代码出现问题,并且我对其进行了更新,则可以刷新该应用程序,以便它发送对javascript文件的新请求,从而获得新版本。

EDIT: 编辑:

I already have the UIWebView and it loads a website. 我已经有了UIWebView并加载了一个网站。 I know how to load js from the main bundle but I need to send a request in the UIWebViewDIdFinishLoad and grab the javascript file from my server to load in the UIWebView. 我知道如何从主捆绑中加载js,但是我需要在UIWebViewDIdFinishLoad中发送请求,并从服务器中获取JavaScript文件以加载到UIWebView中。

You have to download the js file with the Alamofire or AFNetworking. 您必须使用Alamofire或AFNetworking下载js文件。 There are very simple methods to download files from the Internet. 有很简单的方法可以从Internet下载文件。 Download it save it and use them to load the web view. 下载并保存并使用它们加载Web视图。

Alamofire Alamofire

AFNetworking AFNetworking

Download 下载

NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];

NSURL *URL = [NSURL URLWithString:@"http://example.com/download.zip"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];

NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
    NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
    // Save this following url to load the file
    return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];
} completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
    NSLog(@"File downloaded to: %@", filePath);
    [[NSUserDefaults standardUserDefaults] setURL:filePath forKey:@"URL_TO_SAVE"];
    [[NSUserDefaults standardUserDefaults] synchronize];

}];
[downloadTask resume];

Load To WebView 加载到WebView

NSURL *URL = [[NSUserDefaults standardUserDefaults] URLForKey:@"URL_TO_SAVE"];
NSString *javaScript = [NSString stringWithContentsOfURL:URL encoding:NSUTF8StringEncoding error: nil];
[webView stringByEvaluatingJavaScriptFromString:javaScript];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM