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-> Bundle Resources 복사 아래의 루트 경로에 참조 이미지를 넣은 경우 제대로 작동하지만 html 파일에 표시된 것처럼 상대 경로와 작동하지 않습니다. . 이 작업을 수행 할 수있는 방법이 있어야합니다. 웹뷰에로드 할 이미지, CSS, 자바 스크립트 파일이 많이 있으며 루트에 모든 것을 가질 필요가 없으며 웹의 모든 참조를 변경하지 않아도됩니다. 앱.
이것은 상대 참조가있는 로컬 HTML을로드 / 사용하는 방법입니다.
- 리소스를 xcode 프로젝트로 드래그하십시오 (파인더 창에서 www라는 폴더를 드래그했습니다). "추가 된 폴더에 대한 그룹 생성"과 "추가 된 폴더에 대한 폴더 참조 생성"의 두 가지 옵션이 있습니다.
- "폴더 참조 작성"옵션을 선택하십시오.
아래 주어진 코드를 사용하십시오. 그것은 매력처럼 작동해야합니다.
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)) )
}
스위프트에서 :
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 (요청)을 사용하여에 대해 조언한다 :
Don’t use this method to load local HTML files; instead, use loadHTMLString:baseURL:.
In this solution, the html is read into a string. The html's url is used to work out the path, and passes that as a base 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)
I've gone back and tested and re-tested this, it appears that the only way I can get it to work (since I have some files in the img folder and some in js/css, etc...) is not to use a relative path to my image in the html and have everything referenced to the bundle folder. What a shame :(.
<img src="myimage.png" />
@sdbrain's answer in Swift 3:
let url = URL.init(fileURLWithPath: Bundle.main.path(forResource: "index", ofType: "html", inDirectory: "www")!)
webView.loadRequest(NSURLRequest.init(url: url) as URLRequest)
In Swift 3.01 using WKWebView:
let localURL = URL.init(fileURLWithPath: Bundle.main.path(forResource: "index", ofType: "html", inDirectory: "CWP")!)
myWebView.load(NSURLRequest.init(url: localURL) as URLRequest)
This adjusts for some of the finer syntax changes in 3.01 and keeps the directory structure in place so you can embed related HTML files.
'Programming' 카테고리의 다른 글
| sqlcmd를 사용하여 SQL Server에서 데이터를 CSV 형식으로 내보내는 방법은 무엇입니까? (0) | 2020.07.13 |
|---|---|
| Visual Studio 프로젝트의 폴더에 대한 "링크로 추가" (0) | 2020.07.13 |
| PHP에서 두 날짜를 어떻게 비교할 수 있습니까? (0) | 2020.07.13 |
| 파이썬 인터프리터 쉘에서 마지막 명령을 반복하는 방법은 무엇입니까? (0) | 2020.07.13 |
| 검색 창 위젯의 배경 드로어 블 변경 (0) | 2020.07.13 |