initWithContentsOfFile已弃用

8 iphone cocoa-touch webview

我想知道我可以使用什么代码而不是initWithContentsOfFile:因为我一直在寻找一些不被弃用但却找不到的东西.我正在尝试在webview中显示本地HTML文件,下面是代码:

- (void)viewDidLoad {
    [super viewDidLoad];

    NSString *htmlPath = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"];
    NSURL *bundleUrl = [NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]];
    NSString *html = [[NSString alloc] initWithContentsOfFile:htmlPath];
    [self.myWebView loadHTMLString:html baseURL:bundleUrl];

}
Run Code Online (Sandbox Code Playgroud)

我收到一条警告说initWithContentsOfFile:已弃用,想知道如何更新它.

小智 16

试试这个:

NSError *error = nil;
NSString *string = [[NSString alloc] initWithContentsOfFile:@"/path/to/file.txt" encoding:NSUTF8StringEncoding error:&error];
Run Code Online (Sandbox Code Playgroud)

  • 完善!非常感谢! (2认同)