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

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가 비어 있습니다. 도움을 주셔서 감사합니다.



답변

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전화로 리소스를 찾았는지 확인하십시오 .


답변

편집 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프로젝트에서 로드 됩니다.


답변

이것에 의해 프로젝트 애셋 (번들)에있는 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]]];

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


답변

나는 당신이 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];
}


답변

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

-(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'


답변

스위프트 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)


답변

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]]];