如何加载 UIWebView
,然后从我的服务器请求 javascript 文件并将其加载到 UIWebView
中?
假设 js 代码出现问题,我更新它,您可以刷新应用程序,以便它发送对 javascript 文件的新请求,您将拥有新版本。
编辑:
我已经有了 UIWebView
并且它加载了一个网站。我知道如何从主包加载 js,但我需要在 UIWebViewDIdFinishLoad 中发送请求并从我的服务器获取 javascript 文件以在 UIWebView 中加载。
最佳答案
您必须使用 Alamofire 或 AFNetworking 下载 js 文件。从 Internet 下载文件的方法非常简单。下载它并保存它并使用它们加载 WebView 。
下载
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];
加载到 WebView
NSURL *URL = [[NSUserDefaults standardUserDefaults] URLForKey:@"URL_TO_SAVE"];
NSString *javaScript = [NSString stringWithContentsOfURL:URL encoding:NSUTF8StringEncoding error: nil];
[webView stringByEvaluatingJavaScriptFromString:javaScript];
关于javascript - 在 UIWebView 中加载一个 javascript 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32536892/