url nsdata not replacing local writetofile JSON

150 views Asked by At

JSON web file is not overwriting and replacing the local JSON file on the App.

-(void)writeJsonToFile
{

    NSURL *fileJSON = [[NSBundle mainBundle] URLForResource:@"data" withExtension:@"json"];
    NSString *filePath = [NSString stringWithFormat:@"%@",fileJSON];

    NSString *stringURL = @"website.com/data.json";
    NSURL *url = [NSURL URLWithString:stringURL];
    NSData *urlData = [NSData dataWithContentsOfURL:url];

    [urlData writeToFile:filePath atomically:YES];

}

The destination for urlData and filePath files match each other. Been looking around the site and other places online, made sure the file path matched.

1

There are 1 answers

0
Lalji On

We can never change the NSBundle file but you can save in to local then try this

-(void)writeJsonToFile
{
    NSString * filePath=[NSString stringWithFormat:@"%@/Documents/data.json",NSHomeDirectory()];
    NSString *stringURL = @"website.com/data.json";
    NSURL *url = [NSURL URLWithString:stringURL];
    NSData *urlData = [NSData dataWithContentsOfURL:url];

    [urlData writeToFile:filePath atomically:YES];
}

This code replacing local JSON file when call. Your JSON file save in your application directory/Documents/ and file name is data.json

website.com/data.json do not return json data, please check it and if needed to change your URL.