Reputation: 488
How do I load a UIWebView
and then request a javascript file from my server and load that into the 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.
EDIT:
I already have the UIWebView
and it loads a website. 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.
Upvotes: 1
Views: 3118
Reputation: 2011
You have to download the js file with the Alamofire or AFNetworking. There are very simple methods to download files from the Internet. Download it save it and use them to load the web view.
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
NSURL *URL = [[NSUserDefaults standardUserDefaults] URLForKey:@"URL_TO_SAVE"];
NSString *javaScript = [NSString stringWithContentsOfURL:URL encoding:NSUTF8StringEncoding error: nil];
[webView stringByEvaluatingJavaScriptFromString:javaScript];
Upvotes: 2