iOS从url下载html文件

时间:2014-09-01 08:01:55

标签: html ios json afnetworking

我需要从服务器url下载html文件并替换为本地html文件。我使用AFNetworking下载文件并存储到Documents文件夹。它正在下载视频&音频文件。但是当我尝试下载html文件时,我得到的错误Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (JSON text did not start with array or object and option to allow fragments not set.) UserInfo=0x83d0730 {NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}

 NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
 NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
 NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:@"solarhtml"];

 if ([[NSFileManager defaultManager] fileExistsAtPath:dataPath])
 [[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error];

 AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

 [manager.requestSerializer setValue:@"application/x-www-form-urlencoded"
 forHTTPHeaderField:@"Content-Type"];

 [manager setResponseSerializer:[AFJSONResponseSerializer serializer]];
 manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html", nil];


 [manager GET:@"http://server.net/projects/index.html"
 parameters:nil
 success:^(AFHTTPRequestOperation *operation, id responseObject) {
 [operation.responseData writeToFile:[dataPath stringByAppendingPathComponent:@"index.html"] atomically:YES];


 NSLog(@"Successfully downloaded file to %@", [NSURL fileURLWithPath:dataPath]);
 NSLog(@"THE RESPONSE: %@", responseObject);


 }
 failure:^(AFHTTPRequestOperation *operation, NSError *error1) {
 NSLog(@"%@", error1);
 }];

访问html文件:

  -(void)estimatesavings:(id)sender{


      if(updateclick==YES){

        web_estimate=[[UIWebView alloc]initWithFrame:CGRectMake(0, 0, 1024, 768)];

        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"index.html"];

        NSURL *targetURL = [NSURL fileURLWithPath:filePath];
        NSURLRequest *request = [NSURLRequest requestWithURL:targetURL];
        [web_estimate loadRequest:request];

        web_estimate.delegate=self;

        [self.view addSubview:web_estimate];

    }else{


    NSString *pathToBundle = [[NSBundle mainBundle] bundlePath];
    NSURL *baseURL = [NSURL fileURLWithPath:pathToBundle];
    NSString *htmlFile = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"];
    NSString *htmlString = [NSString stringWithContentsOfFile:htmlFile encoding:NSUTF8StringEncoding error:nil];
    //CGRect fullScreenRect=[[UIScreen mainScreen]applicationFrame];
    web_estimate=[[UIWebView alloc]initWithFrame:CGRectMake(0, 0, 1024, 768)];
    [web_estimate loadHTMLString:htmlString baseURL:baseURL];



    web_estimate.delegate=self;
    [self.view addSubview:web_estimate];

    }


    }

ERROR:

copy failed: Error Domain=NSCocoaErrorDomain Code=4 "The operation couldn’t be completed. (Cocoa error 4.)" UserInfo=0x83c8b50 {NSSourceFilePathErrorKey=/Users/ranganathagv/Library/Application Support/iPhone Simulator/6.1/Applications/CEDFEBEB-2A5C-40A9-8965-761689FD83C2/ActewAGL.app/index.html, NSUserStringVariant=(
    Copy
), NSFilePath=/Users/ranganathagv/Library/Application Support/iPhone Simulator/6.1/Applications/CEDFEBEB-2A5C-40A9-8965-761689FD83C2/ActewAGL.app/index.html, NSDestinationFilePath=/Users/ranganathagv/Library/Application Support/iPhone Simulator/6.1/Applications/CEDFEBEB-2A5C-40A9-8965-761689FD83C2/Documents/solarhtml/index.html, NSUnderlyingError=0x83c89c0 "The operation couldn’t be completed. No such file or directory"}c

1 个答案:

答案 0 :(得分:0)

有两个问题:

  1. 尝试使用AFJSONResponseSerializer并更改acceptableContentTypes将无效,因为AFJSONResponseSerializer会接受回复,但仍会尝试解析JSON。相反,您应该只使用AFHTTPResponseSerializer。有关详细信息,请参阅https://stackoverflow.com/a/21621530/1271826

  2. 另一个问题在于你的开放日常工作。您应该在Documents文件夹中打开该文件,而不是仅从捆绑包中打开文件。您甚至可能希望将文件从捆绑包复制到Documents文件夹(如果尚未下载的话)。

    例如:

    NSString *documentsFolder  = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    NSString *solarFolder      = [documentsFolder stringByAppendingPathComponent:@"solarhtml"];
    NSString *documentsPath    = [solarFolder stringByAppendingPathComponent:@"index.html"];
    NSString *bundlePath       = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"];
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    if (![fileManager fileExistsAtPath:documentsPath]) {
        NSError *error;
        if (![fileManager fileExistsAtPath:solarFolder]) {
            if (![fileManager createDirectoryAtPath:solarFolder withIntermediateDirectories:YES attributes:nil error:&error]) {
                NSLog(@"create folder failed: %@", error);
            }
        }
        if (![fileManager copyItemAtPath:bundlePath toPath:documentsPath error:&error]) {
            NSLog(@"copy failed: %@", error);
        }
    }
    
    NSString *htmlString = [NSString stringWithContentsOfFile:documentsPath encoding:NSUTF8StringEncoding error:nil];
    web_estimate=[[UIWebView alloc]initWithFrame:CGRectMake(0, 0, 1024, 768)];
    [web_estimate loadHTMLString:htmlString baseURL:baseURL];
    

    这样,如果文件根本没有被下载,这将在尝试打开文件之前复制文件包,如果有必要的话。