SriTeja Chilakamarri
SriTeja Chilakamarri

Reputation: 2703

Can I write files into a HTML file using Xcode and then load it on a web view?

I have a file named editor.html as of right now. Its static and loads the HTML content onto the web view whenever it is called.

But as my HTML code (fixing bugs /adds new features) keeps changing always I have an API so that I can add this HTML and CSS code dynamically using the Json response.

Now in Xcode can I create / edit my existing editor.html file to populate it with the string I received from this API ?

I tried this code for testing purpose and it does not write anything, but users have responded pretty positively on that comment saying it works, can anyone please help me on this ?

NSError *error;
NSString *stringToWrite = @"/Users/name/Desktop/testHTML";
NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:@"myfile.txt"];
NSString *contents = [NSString stringWithFormat:@"This is test for html"];

[stringToWrite writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error];

Upvotes: 1

Views: 2122

Answers (1)

Dattatray Deokar
Dattatray Deokar

Reputation: 2103

If your file is in App bundle then first thing you have to do is copy your file into documents directory of your app at runtime then you can replace content downloaded from API inside your file.

Copy File from App bundle to document directory, replace file name and file extension with your file type.

NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;

NSString *dataPath = [[self applicationDocumentsDirectory] stringByAppendingPathComponent:@"tessdata"];
NSLog(@"Datapath is %@", dataPath);

// If the expected store doesn't exist, copy the default store.    
    if ([fileManager fileExistsAtPath:dataPath] == NO)
    {
        NSString *tessdataPath = [[NSBundle mainBundle] pathForResource:@"eng" ofType:@"traineddata"];
        [fileManager copyItemAtPath:tessdataPath toPath:dataPath error:&error];

    }


-(NSString*) applicationDocumentsDirectory{
    // Get the documents directory
    NSArray *dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *docsDir = [dirPaths objectAtIndex:0];
    return docsDir;
}

Write Data into File

NSError *error;
NSString *stringToWrite = @"1\n2\n3\n4";
NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:@"myfile.txt"];
[stringToWrite writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error];

Upvotes: 1

Related Questions