Кэширование UIWebView - PullRequest
       6

Кэширование UIWebView

0 голосов
/ 04 июля 2011

Я очень новичок в разработке для iphone, и я пытаюсь получить веб-представление для кеширования на устройство, чтобы оно работало там даже при закрытии приложения, а затем перезагружало данные при повторном запуске приложения. Я также хотел бы перезагрузить данные в кэш каждые 2 недели.

Большое спасибо, Thomas

1 Ответ

2 голосов
/ 09 июля 2011

в результате многочисленных поисков и расспросов друзей мне удалось найти код, и хотя я поделился им со всеми

Objective-C

- (void) cacheFile
{
    //Create the file/directory pointer for the storage of the cache.
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    self.dataPath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"cache.html"];

    //Check to see if a file exists a the location
    if ([[NSFileManager defaultManager] fileExistsAtPath:dataPath]) {
       //Code for customising when the cache reloads would go here.
    }
    else
    {
        //If no file exists write the html cache to it
        //Download and write to file
        NSURL *cacheUrl = [NSURL URLWithString:@"INSERT WEB URL HERE"];
        NSData *cacheUrlData = [NSData dataWithContentsOfURL:cacheUrl];
        [cacheUrlData writeToFile:dataPath atomically:YES]; 
    }
//Run the load web view function.
[self loadWebView];
}


- (void) loadWebView
{
//Load up the web view from the cache.
[WebView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:dataPath]]];

}

Swift 3

func cacheFile() {
    //Create the file/directory pointer for the storage of the cache.
    let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
    guard let dataPath = paths.first?.appending("cache.html") else {
        return
    }

    //Check to see if a file exists a the location
    if FileManager.default.fileExists(atPath: dataPath) {
        //Code for customising when the cache reloads would go here.
    } else if let cacheUrl = URL(string: "INSERT WEB URL HERE") {
        //If no file exists write the html cache to it
        //Download and write to file
        do {
            let cacheUrlData = try Data(contentsOf: cacheUrl)
            try cacheUrlData.write(to: URL(fileURLWithPath: dataPath), options: Data.WritingOptions.atomic)
        } catch {
            print("Problem with cacheUrlData")
        }
    }

    //Run the load web view function.
    loadWebView(dataPath: dataPath)
}

func loadWebView(dataPath: String) {
    webView.loadRequest(URLRequest(url: URL(fileURLWithPath: dataPath)))
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...