2011-07-04 115 views
0

我對iphone開發非常陌生,我試圖獲得一個web視圖來緩存到設備上,以便即使在應用程序關閉時仍然會響起,然後在應用程序再次啓動時重新加載數據。我也希望它每兩週重新加載緩存中的數據。緩存一個UIWebView

非常感謝, 托馬斯

+0

你可能不想緩存視圖,但數據(模型) – Felix

+0

以及我需要緩存視圖,因爲其中一個頁面是一個Web視圖,並給出了信息的負載,我希望這可以離線使用,不會在每次加載時都使用數據,但也可以在無需將更新推送到應用商店的情況下進行更新。 –

+0

對於最後一條評論(對於編程來說真的很新穎(對我來說還是新手))並且回頭看它我知道我需要緩存網頁而不是視圖 –

回答

2

通過大量的摸索和詢問朋友的我好不容易纔找到的代碼,雖然,我會和大家一起

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))) 
}