0

I need to download the html file from server url and replace to local html file. I'm using AFNetworking to download the file and store to Documents folder. It's downloading video & audio files. But when i try to download the html files i'm getting below error 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);
 }];

Access html file:

  -(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
user3743552
  • 143
  • 3
  • 13
  • Why did you use `AFJSONResponseSerializer` for JSON if your answer is not a JSON? – Larme Sep 01 '14 at 08:17
  • but i use same for download the .mp4 file from internet. It's working..but why it's not working for html file? – user3743552 Sep 01 '14 at 08:26
  • It's working..But it's not replacing my local html file. Successfully downloaded file to file://localhost/Users/ranganathagv/Library/Application%20Support/iPhone%20Simulator/6.1/Applications/0DFCC406-FAF9-4F12-9F25-3EAE12CF7B9F/Documents/solarhtml/ – user3743552 Sep 01 '14 at 08:34
  • No need AFNetwork for this, try stringWithContentsOfURL: NSString *content = [NSString stringWithContentsOfURL:[NSURL URLWithString:requestString] encoding:NSUTF8StringEncoding error:error]; – Ilya K. Sep 01 '14 at 08:35
  • @user3743552 It's hard to reconcile "it's working" and "it's not replacing my local html file". Where precisely is this failing? Have you looked at that file at that location? Did the actual file content change (i.e. is the problem that you're failing to load the local copy again)? Or did the file not change (i.e. is the problem either caching or failure to save)? It has to be one or the other. (BTW, thanks for deleting the duplicate question!) – Rob Sep 01 '14 at 08:55
  • I have index.html file inside solarhtml folder. Then i'm downloading the html file from server url and replacing the index.html file inside solarhtml folder – user3743552 Sep 01 '14 at 08:56
  • @Rob: check my updated code. I have button to load the index.html file.. – user3743552 Sep 01 '14 at 09:12
  • ok. So, do i need to over write the index.html file in bundle? How can i do this? – user3743552 Sep 01 '14 at 09:20
  • I need to load index.html file from local..once update done with button i need to load updated index.html file – user3743552 Sep 01 '14 at 09:23
  • use `dataWithContentsOfURL:` or one of the similar simple calls – Fattie May 03 '16 at 15:22

1 Answers1

0

There were two problems:

  1. The attempt to use AFJSONResponseSerializer and changing the acceptableContentTypes will not work, because the AFJSONResponseSerializer will accept the response, but will still try to parse the JSON. Instead, you should just use AFHTTPResponseSerializer instead. See https://stackoverflow.com/a/21621530/1271826 for more information.

  2. The other problem rests in your open routine. Rather than just opening the file from the bundle, you should open the file in the Documents folder. You might even want to copy the file from the bundle to the Documents folder (in case it hasn't been downloaded yet).

    For example:

    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];
    

    This way, if the file hasn't been downloaded at all, this will copy the file from the bundle before trying to open it, if necessary.

Community
  • 1
  • 1
Rob
  • 415,655
  • 72
  • 787
  • 1,044
  • Did you create the `solarhtml` folder? I adjusted my code sample to illustrate how you might do that. You'd also want similar "if `solarhtml` folder doesn't, create it" logic in the download routine. – Rob Sep 01 '14 at 10:01