iOS download and save HTML file

前端 未结 4 806
悲哀的现实
悲哀的现实 2020-12-05 05:12

I am trying to download a webpage (html) then display the local html that has been download in a UIWebView.

This is what I have tried -

NSString *st         


        
相关标签:
4条回答
  • 2020-12-05 05:59

    Your app is a folder with a .app extension on the end. On the iPhone once it is installed you can't change this folder, hence why you save it to the documents directory.

    In your example code you save the file to Documents/index.html and ask it to load appname.app/index.html.

    [NSBundle mainBundle] doesn't give you the documents directory it gives you (i think) the .app folder (though it might be the folder that contains the app, documents, and other folders).

    To give you'll want to change this line.

    [web loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"]isDirectory:NO]]];
    

    To (providing this is the same method as the rest of the code, else recreate the object 'filePath')

    [web loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:filePath isDirectory:NO]]];
    
    0 讨论(0)
  • 2020-12-05 06:03

    Here is the Swift 2.x version:

        var paths: [AnyObject] = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
        var filePath: String = "\(paths[0])/\("index.html")"
    
        // Download and write to file
        var url: NSURL = NSURL(string: "http://www.google.nl")!
        var urlData: NSData = NSData.dataWithContentsOfURL(url)
        urlData.writeToFile(filePath, atomically: true)
    
        // Load file in UIWebView
        web.loadRequest(NSURLRequest(URL: NSURL.fileURLWithPath(filePath)))
    
    0 讨论(0)
  • 2020-12-05 06:06

    The path passed to the UIWebView is incorrect, like Freerunnering mentioned, try this instead:

    // Determile cache file path
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *filePath = [NSString stringWithFormat:@"%@/%@", [paths objectAtIndex:0],@"index.html"];   
    
    // Download and write to file
    NSURL *url = [NSURL URLWithString:@"http://www.google.nl"];
    NSData *urlData = [NSData dataWithContentsOfURL:url];
    [urlData writeToFile:filePath atomically:YES];
    
    // Load file in UIWebView
    [web loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:filePath]]];      
    

    Note: Correct error-handling needs to be added.

    0 讨论(0)
  • 2020-12-05 06:18

    NSDocumentDirectory will be backed up to iCloud. You might be better off using NSCachesDirectory https://developer.apple.com/library/ios/#qa/qa1719/_index.html

    0 讨论(0)
提交回复
热议问题