【问题标题】:Can I write files into a HTML file using Xcode and then load it on a web view?我可以使用 Xcode 将文件写入 HTML 文件,然后将其加载到 Web 视图中吗?
【发布时间】:2017-11-15 05:42:13
【问题描述】:

我现在有一个名为 editor.html 的文件。它是静态的,并在调用时将 HTML 内容加载到 Web 视图中。

但是随着我的 HTML 代码(修复错误/添加新功能)不断变化,我有一个 API,以便我可以使用 Json 响应动态添加此 HTML 和 CSS 代码。

现在我可以在 Xcode 中创建/编辑我现有的 editor.html 文件以使用我从该 API 收到的字符串填充它吗?

我出于测试目的尝试了这段代码,它没有写任何东西,但用户对该评论的反应非常积极,说它有效,有人可以帮我吗?

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

【问题讨论】:

    标签: html ios objective-c xcode


    【解决方案1】:

    如果您的文件在 App bundle 中,那么您要做的第一件事就是在运行时将文件复制到应用程序的文档目录中,然后您可以在文件中替换从 API 下载的内容。

    将文件从 App bundle 复制到文档目录,将文件名和文件扩展名替换为您的文件类型。

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

    将数据写入文件

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

    【讨论】:

    • 谢谢你,如果可能的话,你能给我提供Objective C等价物吗,因为我的项目在Obj C中。
    • 我没有转换等效的objc代码,你需要转换它。
    • 好的,谢谢,试试这个然后回来:)
    • 如果你不介意,你能解释一下每个函数到底在做什么吗?
    • getDocumentDirectory 返回应用中 Document 目录的路径
    猜你喜欢
    • 2019-11-19
    • 2021-11-05
    • 2022-01-13
    • 2013-12-26
    • 1970-01-01
    • 1970-01-01
    • 2020-12-05
    • 1970-01-01
    • 2023-04-06
    相关资源
    最近更新 更多