UIWebView에 로컬 html 파일을로드하는 방법


165

UIWebView에 html 파일을로드하려고하는데 작동하지 않습니다. 단계는 다음과 같습니다. 프로젝트에 html_files라는 폴더가 있습니다. 그런 다음 인터페이스 빌더에서 webView를 작성하고 viewController에서 콘센트를 지정했습니다. 이것은 html 파일을 추가하는 데 사용하는 코드입니다.

-(void)viewDidLoad
{
    NSString *htmlFile = [[NSBundle mainBundle] pathForResource:@"sample" ofType:@"html" inDirectory:@"html_files"];
    NSData *htmlData = [NSData dataWithContentsOfFile:htmlFile];
    [webView loadData:htmlData MIMEType:@"text/html" textEncodingName:@"UTF-8" baseURL:[NSURL URLWithString:@""]];
    [super viewDidLoad];
}

작동하지 않으며 UIWebView가 비어 있습니다. 도움을 주셔서 감사합니다.

답변:


272

NSString을 사용하고 다음과 같이 html 문서를로드하는 것이 좋습니다.

목표 -C

NSString *htmlFile = [[NSBundle mainBundle] pathForResource:@"sample" ofType:@"html"];
NSString* htmlString = [NSString stringWithContentsOfFile:htmlFile encoding:NSUTF8StringEncoding error:nil];
[webView loadHTMLString:htmlString baseURL: [[NSBundle mainBundle] bundleURL]];

빠른

let htmlFile = NSBundle.mainBundle().pathForResource("fileName", ofType: "html")
let html = try? String(contentsOfFile: htmlFile!, encoding: NSUTF8StringEncoding)
webView.loadHTMLString(html!, baseURL: nil) 

스위프트 3에는 약간의 변화가 있습니다 :

let htmlFile = Bundle.main.path(forResource: "intro", ofType: "html")
let html = try? String(contentsOfFile: htmlFile!, encoding: String.Encoding.utf8)
webView.loadHTMLString(html!, baseURL: nil)

시도해 보았 니?

또한 pathForResource:ofType:inDirectory전화로 리소스를 찾았는지 확인하십시오 .


작동하지 않습니다. NSLog (@ "% @", htmlFile); 확인하고 null이라고 말합니다.
— madcoderz

따라서 리소스를 찾을 수 없습니다. NSString * htmlFile = [[NSBundle mainBundle] pathForResource : @ "sample"ofType : @ "html"]; inDirectory없이
— user478681

inDirectory가 없으면 iPhone Simulator / 4.3.2 / Applications / 49351078-9423-4A24-8E58-B2A059961097 / WebviewTest.app / sample.html 이지만 HTML이 여전히 비어있는 화면에 표시되지 않았습니다. 다른 것을 놓치고 있습니까? 샘플 프로젝트는 다음과 같습니다. http://www.box.net/shared/rb05b4ppjnbof1r33gh7
— madcoderz

3
당신은 당신의 webview의 프레임을 수정해야합니다
— user478681

3
이 답변은 많은 투표권을 가지고 있지만 구식 인 것 같습니다. 이 방법을 사용하면 로컬 이미지 및 CSS 자산이로드되지 않습니다. 대신 이 답변을 참조하십시오 .
— paulmelnikow

90

편집 2016년 5월 27일 - loadRequest노출하는 "보편적 인 크로스 사이트 스크립팅 취약점을 해결합니다." 로드하는 모든 단일 자산을 소유해야합니다. 잘못된 스크립트를로드하면 원하는 것을로드 할 수 있습니다.

로컬로 작업하기 위해 상대 링크가 필요한 경우 다음을 사용하십시오.

NSURL *url = [[NSBundle mainBundle] URLForResource:@"my" withExtension:@"html"];
[webView loadRequest:[NSURLRequest requestWithURL:url]];

번들은 찾을 프로젝트의 모든 하위 디렉토리를 검색합니다 my.html. (빌드 타임에 디렉토리 구조가 평평 해짐)

my.html태그가 있으면 <img src="some.png">webView가 some.png프로젝트에서 로드 됩니다.


4
이 페이지에서 허용되는 답변을 얻을 수 없었지만이 방법은 처음에는 효과가있었습니다. 원래 답변 이후 iOS가 발전했다고 생각합니다. 감사.
— James

이 답변에 감사드립니다. 이것과 허용되는 대답의 차이점은 HTML 문서 작업의 링크입니다.
— Amy

2
Apple에 따르면 보안 공격에 취약하지 않도록하려면 loadHTMLString : baseURL :을 사용하여 로컬 HTML 파일을로드하십시오. loadRequest :를 사용하지 마십시오.
— ED-209

수락 된 답변이 효과가 없습니다. 감사합니다 @neal Ehardt이 대답은 나를 위해 일하고 있습니다.
— Mihir Oza

html 파일이 폴더 안에없는 경우에만 작동합니다.
— Renan Franca

40

이것에 의해 프로젝트 애셋 (번들)에있는 html 파일을 webView에로드 할 수 있습니다.

 UIWebView *web = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, 460)];
    [web loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] 
                                pathForResource:@"test" ofType:@"html"]isDirectory:NO]]];

이것이 당신에게 유용 할 수 있습니다.


그것은 내가하는 유일한 차이점은 프로그래밍 방식으로 webView를 만들고 있다는 것입니다. 어쨌든 고마워
— madcoderz

NSLog에서 해당 HTML 파일 검사 경로를 가져옵니다.
— AJPatel

html 파일의 대상 멤버십을 확인해야합니다. 그렇지 않으면 다음 예외가 발생합니다.-포착되지 않은 예외 'NSInvalidArgumentException'으로 인해 앱 종료 중 이유 : '***-[NSURL initFileURLWithPath : isDirectory :] : nil 문자열 매개 변수'
— Durai Amuthan. H

9

나는 당신이 allocate당신의 webview첫 번째 를 필요로 하고 초기화 한다고 생각합니다 : :

- (void)viewDidLoad
{
    NSString *htmlFile = [[NSBundle mainBundle] pathForResource:@"sample" ofType:@"html" inDirectory:@"html_files"];
    NSData *htmlData = [NSData dataWithContentsOfFile:htmlFile];
    webView = [[UIWebView alloc] init];
    [webView loadData:htmlData MIMEType:@"text/html" textEncodingName:@"UTF-8" baseURL:[NSURL URLWithString:@""]];

    [super viewDidLoad];
}

8

간단한 복사 붙여 넣기 코드 스 니펫 :

-(void)LoadLocalHtmlFile:(NSString *)fileName onWebVu:(UIWebView*)webVu
{
    [webVu loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle]pathForResource:fileName ofType:@"html"]isDirectory:NO]]];
}

노트 :

html 파일의 Target 멤버쉽 을 확인하십시오. 그렇지 않으면 다음 예외가 발생합니다.

여기에 이미지 설명을 입력하십시오

잡히지 않은 예외로 인해 앱 종료

'NSInvalidArgumentException', reason: '*** -[NSURL initFileURLWithPath:isDirectory:]: nil string parameter'


6

스위프트 3과 스위프트 4의 경우 :

let htmlFile = Bundle.main.path(forResource: "name_resource", ofType: "html")
let html = try! String(contentsOfFile: htmlFile!, encoding: String.Encoding.utf8)
self.webView.loadHTMLString(html, baseURL: nil)

<img src = "..."/>와 같은 링크 된 파일을로드하지 않습니다
— Pierre F

5
UIWebView *web=[[UIWebView alloc]initWithFrame:self.view.frame];
    //[self.view addSubview:web];
    NSString *filePath=[[NSBundle mainBundle]pathForResource:@"browser_demo" ofType:@"html" inDirectory:nil];
    [web loadRequest:[NSURLRequest requestWhttp://stackoverflow.com/review/first-postsithURL:[NSURL fileURLWithPath:filePath]]];

4

동일한 코드가 나를 위해 작동하기 때문에 HTML 파일이 UTF-8 인코딩을 지원하지 않을 수 있습니다.

또는 다음 코드 줄을 사용할 수도 있습니다.

NSString *htmlFile = [[NSBundle mainBundle] pathForResource:@"Notes For Apple" ofType:@"htm" inDirectory:nil];
NSString* htmlString = [NSString stringWithContentsOfFile:htmlFile encoding:NSUTF8StringEncoding error:nil];
[WebView loadHTMLString:htmlString baseURL:nil];

4

Jquery로 HTML 파일을 작동시키는 방법은 다음과 같습니다.

 _webview=[[UIWebView alloc]initWithFrame:CGRectMake(0, 0, 320, 568)];
    [self.view addSubview:_webview];

    NSString *filePath=[[NSBundle mainBundle]pathForResource:@"jquery" ofType:@"html" inDirectory:nil];

    NSLog(@"%@",filePath);
    NSString *htmlstring=[NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];

    [_webview loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:filePath]]];
                         or
    [_webview loadHTMLString:htmlstring baseURL:nil];

요청 중 하나를 사용하여 UIWebview에서 HTML 파일을 호출 할 수 있습니다.


3

"html_files"가 Xcode의 그룹뿐만 아니라 앱의 기본 번들에있는 디렉토리인지 확인하십시오.


3

신속한 방법으로이를 수행하는 새로운 방법입니다. UIWebView는 더 이상 없으며 WKWebView는 웹 페이지를로드하는 새로운 클래스이므로 Safari 기능을 웹보기에 제공합니다.

    import WebKit

    let preferences = WKPreferences()
    preferences.javaScriptCanOpenWindowsAutomatically = false

    let configuration = WKWebViewConfiguration()
    configuration.preferences = preferences

    let webView = WKWebView(frame: self.view.bounds, configuration: configuration)
    let request = NSURLRequest(URL: NSURL(string: "http://nshipster.com"))
    webView.loadRequest(request)

3
Swift iOS:

 // get server url from the plist directory
        var htmlFile = NSBundle.mainBundle().pathForResource("animation_bg", ofType: "html")!
        var htmlString = NSString(contentsOfFile: htmlFile, encoding: NSUTF8StringEncoding, error: nil)
        self.webView.loadHTMLString(htmlString, baseURL: nil)

3
[[NSBundle mainBundle] pathForResource:@"marqueeMusic" ofType:@"html"];

이 늦을 수 있지만에서 파일이있는 경우 pathForResource입니다 nil당신은 그것을 추가해야합니다 Build Phases > Copy Bundle Resources.

여기에 이미지 설명을 입력하십시오


2

여기 스위프트 3이 있습니다.

    if let htmlFile = Bundle.main.path(forResource: "aa", ofType: "html"){
        do{
            let htmlString = try NSString(contentsOfFile: htmlFile, encoding:String.Encoding.utf8.rawValue )
            messageWebView.loadHTMLString(htmlString as String, baseURL: nil)
        }
        catch _ {
        }
    }

1
if let htmlFile = NSBundle.mainBundle().pathForResource("aa", ofType: "html"){
    do{
        let htmlString = try NSString(contentsOfFile: htmlFile, encoding:NSUTF8StringEncoding )
        webView.loadHTMLString(htmlString as String, baseURL: nil)
    }
    catch _ {
    }
}

0

Swift 2.0에서 @ user478681의 답변은 다음과 같습니다.

    let HTMLDocumentPath = NSBundle.mainBundle().pathForResource("index", ofType: "html")
    let HTMLString: NSString?

    do {
        HTMLString = try NSString(contentsOfFile: HTMLDocumentPath!, encoding: NSUTF8StringEncoding)
    } catch {
        HTMLString = nil
    }

    myWebView.loadHTMLString(HTMLString as! String, baseURL: nil)

경로 / 파일 없음 오류를 테스트하기 위해 let을 사용하는 것이 좋습니다.
— ingconti

0

모든 파일 (html 및 리소스)을 디렉토리 (내 "수동")에 넣습니다. 다음으로, "지원 파일"을 통해 디렉토리를 XCode로 끌어다 놓으십시오. "필요한 경우 항목 복사"및 "폴더 참조 작성"옵션을 확인해야합니다. 다음으로 간단한 코드를 작성하십시오.

NSURL *url = [[NSBundle mainBundle] URLForResource:@"manual/index" withExtension:@"html"];
[myWebView loadRequest:[NSURLRequest requestWithURL:url]];

주의 @"manual/index", manual 은 내 디렉토리의 이름입니다 !! 전부다 !!!! 내 하찮은 영어 실력에 죄송하다는 말씀을 드리고 싶습니다...

===================================================== =====================

Hola desde Costa Rica. Ponga los archivos (html y demás recursos) 및 director (en mi caso lo llamé 매뉴얼), luego, arrastre y suelte en XCode, 부드러운 "지원 파일". 사용 된 debes seleccionar las opciones "필요한 경우 항목 복사"y "폴더 참조 작성".

NSURL *url = [[NSBundle mainBundle] URLForResource:@"manual/index" withExtension:@"html"];
[myWebView loadRequest:[NSURLRequest requestWithURL:url]];

Presta atención a @"manual/index", manual es el nombre de mi directorio !!


0

프로젝트가 커지면 HTML 페이지가 하위 폴더에있는 파일을 참조 할 수 있도록 구조가 필요할 수 있습니다.

html_files폴더를 Xcode로 드래그 하고 폴더 참조 작성 옵션을 선택 한다고 가정하면 다음 Swift 코드는 WKWebView지원되는 폴더 구조도 지원합니다.

import WebKit

@IBOutlet weak var webView: WKWebView!

if let path = Bundle.main.path(forResource: "sample", ofType: "html", inDirectory: "html_files") {
    webView.load( URLRequest(url: URL(fileURLWithPath: path)) )
}

이 수단 귀하의 경우 sample.html파일이 포함 <img src="subfolder/myimage.jpg">태그, 다음 이미지 파일 myimage.jpg에서 subfolder또한로드되어 표시됩니다.

크레딧 : https://stackoverflow.com/a/8436281/4769344

당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.