2017-10-09 71 views
0

始終保存零本地HTML文件,我在項目的根目錄我的html文件無法加載在文件路徑迅速4

let myWebView:UIWebView = UIWebView(frame: CGRect(x:0, y:0, width: UIScreen.main.bounds.width, height:UIScreen.main.bounds.height)) 
      self.view.addSubview(myWebView) 

     do { 
      guard let filePath = Bundle.main.path(forResource: "iphone_help", ofType: "html") 
       else { 
        print ("File reading error") 
        return 
      }    
      let contents = try String(contentsOfFile: filePath, encoding: .utf8) 
      let baseUrl = URL(fileURLWithPath: filePath) 
      webView.loadHTMLString(contents as String, baseURL: baseUrl) 
     } 

     catch { 
      print ("File HTML error") 
     } 
+0

你能告訴你的錯誤? –

+0

沒有錯誤,但始終將文件路徑存儲爲零 –

+0

我必須通過使用構建階段來添加我的html文件 –

回答

0
func loadWebView(htmlString : String) { 
     //Give HTML file a name: 
     //Constants.kTempFiled 

     let htmlFileName: NSString = "file.html" 

     //Create a reference to the temporary directory that will store the HTML file: 
     let tempDirectory: NSString = NSTemporaryDirectory() as NSString 

     //Append reference temporary directory to include HTML file name: 
     let htmlFilePath: NSString = tempDirectory.appendingPathComponent(htmlFileName as String) as NSString as NSString 

     //Convert appended temporary directory NSString to an NSURL object: 
     let htmlUrl = NSURL(fileURLWithPath: htmlFilePath as String) 


     //Below, HTML string is written to a file: 
     do { try htmlString.write(toFile: htmlFilePath as String, atomically: true, encoding: String.Encoding.utf8) } 
     catch { } 

     //HTML file URL is fetched and displayed in UIWebView: 
     webView.loadRequest(NSURLRequest(URL: htmlUrl)) 

    }