【问题标题】:Xcode UIWebView local HTMLXcode UIWebView 本地 HTML
【发布时间】:2013-03-27 08:30:50
【问题描述】:

我知道 HTML、javascript、CSS……但我想使用 HTML5 制作原生/混合 iPhone 应用程序,但不使用 PhoneGap 或 Nimblekit 之类的东西。 我以前从未编写过真正的(不是网络应用程序)iPhone 应用程序,所以我对 Xcode 真的一无所知。 我已经用我找到的教程制作了一个 UIWebView,但它显示了一个网站(apple.com)。 我怎样才能使它显示一个本地文件(index.html)?

我在 ViewController.m 中 (void)viewDidLoad 下的代码:

    [super viewDidLoad];
    NSString *fullURL = @"html/index.html";
    NSURL *url = [NSURL URLWithString:fullURL];
    NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
    [_viewWeb loadRequest:requestObj];

【问题讨论】:

    标签: iphone html xcode uiwebview local


    【解决方案1】:

    你有两个选择:

    像这样直接插入 HTML:

    UIWebView *wv = [[UIWebView alloc] init]; 
    [wv loadHTMLString:@"<html><body>YOUR-TEXT-HERE</body></html>" baseURL:nil];
    

    加载项目中存在的 html 文件:

    UIWebView *wv = [[UIWebView alloc] init];
    NSURL *htmlFile = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"test" ofType:@"html"] isDirectory:NO];
    [wv loadRequest:[NSURLRequest requestWithURL:htmlFile]]; 
    

    如果您希望您的示例正常工作,请将您发送的代码替换为:

    [super viewDidLoad];
    NSURL *htmlFile = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"]];
    [_viewWeb loadRequest:[NSURLRequest requestWithURL:htmlFile]];
    

    【讨论】:

    • 感谢您的回答,但这真的很像我第一次在 Xcode 中制作东西。您能告诉我第二件事我必须完全替换什么吗? :)
    • @Eli Ganem:非常感谢!惊人的!你刚刚解决了我的一个大难题。
    【解决方案2】:

    对于 Swift 3:

    @IBOutlet var webView: UIWebView!
    override func viewDidLoad() {
    super.viewDidLoad()
    let URL = Bundle.main.url(forResource: "file name", withExtension: "html")
    let request = NSURLRequest(url: URL! as URL)
    webView.loadRequest(request as URLRequest)
    }
    

    【讨论】:

      【解决方案3】:

      您可以从项目包中加载本地 html 文件,如下所示

      NSURLRequest *requestObj = [NSURLRequest requestWithURL:[[NSBundle mainBundle] URLForResource:@"index" withExtension:@"html"]];
      [myweb loadRequest:requestObj];
      

      【讨论】:

        猜你喜欢
        • 2011-10-16
        • 2017-03-22
        • 1970-01-01
        • 1970-01-01
        • 2014-09-22
        • 2013-06-08
        • 2015-07-27
        • 2011-02-08
        • 1970-01-01
        相关资源
        最近更新 更多