[ios] uiwebview에서 로컬 HTML을 사용하여 상대 경로에서 리소스로드

매우 간단한 테스트 페이지 (test.html)를로드하는 uiwebview가있는 매우 간단한 iOS 앱이 있습니다.

<html>
<body>
<img src="img/myimage.png" />
</body>
</html>

이 test.html 파일을 웹보기에로드합니다.

NSURL *url = [[NSBundle mainBundle] URLForResource:@"test" withExtension:@"html"];
NSString *html = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
NSURL *baseUrl = [NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]];
[webView loadHTMLString:html baseURL:baseUrl];

상대 경로없이 이미지를 참조하고 참조 된 이미지를 XCode 내의 Targets-> Copy Bundle Resources 아래의 루트 경로에 넣으면 제대로 작동하지만 내 html 파일에 표시된대로 상대 경로에서 작동하도록 가져올 수 없습니다. . 이 작업을 수행하는 방법이 있어야합니다. 웹뷰에로드하고 싶은 이미지, CSS, 자바 스크립트 파일이 많으며 루트에 모든 것을 포함하지 않고 웹의 모든 참조를 변경해야합니다. 앱.



답변

상대 참조가있는 로컬 html을로드 / 사용하는 방법입니다.

  1. 리소스를 xcode 프로젝트로 드래그하면 (파인더 창에서 www라는 폴더를 드래그했습니다) “추가 된 폴더에 대한 그룹 생성”및 “추가 된 폴더에 대한 폴더 참조 생성”옵션이 두 가지 표시됩니다.
  2. “폴더 참조 생성 ..”옵션을 선택합니다.
  3. 아래 주어진 코드를 사용하십시오. 매력처럼 작동해야합니다.

    NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"index" ofType:@"html" inDirectory:@"www"]];
    [webview loadRequest:[NSURLRequest requestWithURL:url]];

이제 html의 모든 관련 링크 (예 : img / .gif, js / .js)가 해결되어야합니다.

스위프트 3

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


답변

Swift에서 :

 func pathForResource(  name: String?, 
                        ofType ext: String?, 
                        inDirectory subpath: String?) -> String?  {

  // **name:** Name of Hmtl
  // **ofType ext:** extension for type of file. In this case "html"
  // **inDirectory subpath:** the folder where are the file. 
  //    In this case the file is in root folder

    let path = NSBundle.mainBundle().pathForResource(             "dados",
                                                     ofType:      "html", 
                                                     inDirectory: "root")
    var requestURL = NSURL(string:path!)
    var request = NSURLRequest(URL:requestURL)

    webView.loadRequest(request)
}


답변

나는 모든 것을 한 줄에 담았고 (나쁘게 알고 있음) 문제가 없었습니다.

[webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"test" 
                                                                                                         ofType:@"html"]
                                                             isDirectory:NO]]];         


답변

나는 단순히 이것을한다 :

    UIWebView *webView = [[[UIWebView alloc] init] autorelease];

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

“index.html”은 상대적으로 이미지, CSS, 자바 스크립트 등을 참조합니다.


답변

신속한 답변 2.

있는 UIWebView 클래스 참조 webView.loadRequest (요청)을 사용하여에 대해 조언한다 :

이 방법을 사용하여 로컬 HTML 파일을로드하지 마십시오. 대신 loadHTMLString : baseURL :을 사용하십시오.

이 솔루션에서 html은 문자열로 읽혀집니다. html의 URL은 경로를 계산하는 데 사용되며 기본 URL로 전달합니다.

let url = bundle.URLForResource("index", withExtension: "html", subdirectory: "htmlFileFolder")
let html = try String(contentsOfURL: url)
let base = url.URLByDeletingLastPathComponent
webView.loadHTMLString(html, baseURL: base)


답변

나는 돌아가서 이것을 테스트하고 다시 테스트했는데, (img 폴더에 일부 파일이 있고 js / css 등에 일부 파일이 있기 때문에) 작동하도록 할 수있는 유일한 방법은 html에서 내 이미지에 대한 상대 경로를 사용하고 모든 것이 번들 폴더를 참조하도록합니다. 부끄러운 일 :(.

<img src="myimage.png" />


답변

@sdbrain의 Swift 3 답변 :

    let url = URL.init(fileURLWithPath: Bundle.main.path(forResource: "index", ofType: "html", inDirectory: "www")!)
    webView.loadRequest(NSURLRequest.init(url: url) as URLRequest)