2014-10-30 16 views
49

Questo mi sta facendo impazzire stamattina presto. Voglio caricare un po 'di HTML locale in una vista web:Carica local html in UIWebView usando swift

class PrivacyController: UIViewController { 

    @IBOutlet weak var webView:UIWebView! 

    override func viewDidLoad() { 
     let url = NSURL(fileURLWithPath: "privacy.html") 
     let request = NSURLRequest(URL: url!) 
     webView.loadRequest(request) 
    } 
} 

Il file HTML si trova nella cartella principale del mio progetto, ma è all'interno di un gruppo. La visione web è vuota per me. Qualche idea che cosa è sbagliato? Sono su xcode 6.1 ed eseguo questo esempio sul mio iphone 6.

+0

Questo può aiutare http://stackoverflow.com/questions/24591926/is-this-a-swift-bug-opening-a-file-in -a-webview – Jhondoe

risposta

54

Per recuperare gli URL per le risorse dell'applicazione, è necessario utilizzare il metodo URLForResource della classe NSBundle.

Swift 2

let url = NSBundle.mainBundle().URLForResource("privacy", withExtension:"html") 

Swift 3

let url = Bundle.main.url(forResource: "privacy", withExtension: "html") 
+0

Il punto critico è che deve essere "privacy" e non "privacy.html". Questo era il motivo per cui non stava funzionando per me. –

6

Aggiungere il file HTML locale nel vostro nome del progetto come home.html, quindi creare l'NSURLRequest utilizzando oggetto NSURL, poi passando la richiesta a webview caricherà l'URL richiesto in webview e se non stai usando storyboard aggiungi l'uiwebview nella vista viewcontroller come il codice qui sotto.

override func viewDidLoad() { 
        super.viewDidLoad() 
        // Do any additional setup after loading the view, typically from a nib. 
        let localfilePath = NSBundle.mainBundle().URLForResource("home", withExtension: "html"); 
        let myRequest = NSURLRequest(URL: localfilePath!); 
        myWebView.loadRequest(myRequest); 
     self.view.addSubview(myWebView) 
    } 

Per maggiori riferimento consultare questa versione Swift http://sourcefreeze.com/uiwebview-example-using-swift-in-ios/

15
// Point UIWebView 
@IBOutlet weak var webView: UIWebView! 

override func viewDidLoad() { 
    super.viewDidLoad() 

    //load a file 
    var testHTML = NSBundle.mainBundle().pathForResource("privacy", ofType: "html") 
    var contents = NSString(contentsOfFile: testHTML!, encoding: NSUTF8StringEncoding, error: nil) 
    var baseUrl = NSURL(fileURLWithPath: testHTML!) //for load css file 

    webView.loadHTMLString(contents, baseURL: baseUrl) 

} 
6

2,1

questo caso comprendono anche Codifica

// load HTML String with Encoding 
let path = NSBundle.mainBundle().pathForResource("policy", ofType: "html") 
do { 
    let fileHtml = try NSString(contentsOfFile: path!, encoding: NSUTF8StringEncoding) 
    webView.loadHTMLString(fileHtml as String, baseURL: nil) 
} 
catch { 

} 
4

Questo è funzionato per me:

@IBOutlet weak var mWebView: UIWebView! 

override func viewDidLoad() { 
    super.viewDidLoad() 
    // Do any additional setup after loading the view, typically from a nib. 

    mWebView.loadRequest(NSURLRequest(URL: NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("fineName", ofType: "html")!))) 

} 

Aggiunto App Transport Security Settings con Dictionary tipo in Info.plist file. Aggiunta anche la sottochiave Allow Arbitrary Loads per Impostazioni protezione trasporto app con tipo Boolean e valore YES.

Here è un tutorial.

CURA

Per Swift 3 (Xcode 8)

mWebView.loadRequest(URLRequest(url: URL(fileURLWithPath: Bundle.main.path(forResource: "test/index", ofType: "html")!))) 
1

È possibile caricare stringa HTML o file HTML locale in UIWebView.stringa

HTML:

func loadHtmlCode() { 
    let htmlCode = "<html><head><title>Wonderful web</title></head> <body><p>wonderful web. loading html code in <strong>UIWebView</strong></></body>" 
    webView.loadHTMLString(htmlCode, baseURL: nil) 
} 

file HTML:

func loadHtmlFile() { 
    let url = NSBundle.mainBundle().URLForResource("contactus", withExtension:"html") 
    let request = NSURLRequest(URL: url!) 
    webView.loadRequest(request) 
} 

dettagli possono essere trovati qui: http://webindream.com/load-html-uiwebview-using-swift/

+0

come mostrare un'immagine in loadHtmlCode(), perché ho provato ma l'immagine sta mostrando vuoto @farhad rubel –

+0

ho provato in questo modo far htmlCode = "Codice Wonderful web

meravigliosa web. Carico HTML in UIWebView

" –

0

Questo ha funzionato per me (Xcode 8, Swift 3)

@IBOutlet weak var webViewer: UIWebView!

override func viewDidLoad() { 
    super.viewDidLoad() 

    let localfilePath = Bundle.main.url(forResource: "homeInfo", withExtension: "html"); 
    let myRequest = NSURLRequest(url: localfilePath!); 
    webViewer.loadRequest(myRequest as URLRequest); 
    self.view.addSubview(webViewer) 
} 
0

per SWIFT 3 Utilizzare questa:

do 
    { 
     let testHTML = Bundle.main.path(forResource: "about", ofType: "html") 
     let contents = try NSString(contentsOfFile: testHTML!, encoding: String.Encoding.utf8.rawValue) 
     let baseUrl = NSURL(fileURLWithPath: testHTML!) //for load css file 

     mWebView.loadHTMLString(contents as String, baseURL: baseUrl as URL) 
    } 
    catch 
    { 

    } 
10

Swift 3: Tipo di sicurezza

@IBOutlet weak var webView: UIWebView! 

override func viewDidLoad() { 
    super.viewDidLoad() 

    // Adding webView content 
    do { 
     guard let filePath = Bundle.main.path(forResource: "myFile", ofType: "html") 
      else { 
       // File Error 
       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") 
    } 
} 

Tenete a mente: NS = Non Swift:]

+0

Grazie si @Peter Kreinz – iLandes

+0

questo dovrebbe essere accettato risposta, funziona come un fascino! – godblessstrawberry

3

Swift 3 con linee :)

if let url = Bundle.main.url(forResource: "privacy", withExtension: "html") { 
    webview.loadRequest(URLRequest(url: url)) 
} 
Problemi correlati