2011年10月3日 星期一

UIWebView讀取本地端檔案

1.把要加入專案的檔案(如HTML、CSS等)拖入專案,並選取create folder reference,這樣才會在專案內建立相對路徑。

2.專案Build之前,記得先Clean一下

程式碼部分
//檢查html路徑是否存在
NSFileManager *fileManager = [[NSFileManager alloc] init];
NSString *appPath = [[NSBundle mainBundle] resourcePath];
NSString *htmlPath = [appPath stringByAppendingPathComponent:@"/GS45X/product/outlander"];
//NSLog(@"%@",htmlPath);

if ([fileManager fileExistsAtPath:htmlPath]) { //如果html的路徑存在

//建立webView
UIWebView* WebView = [[UIWebView alloc] initWithFrame:CGRectMake(0.0, 0.0, 768, 1024)];

//建立baseUrl
NSURL *baseURL = [NSURL fileURLWithPath:htmlPath];

//index.html的路徑
NSString *filePath = [htmlPath stringByAppendingPathComponent:@"index.html"];
//NSLog(@"%@",filePath);
NSData *htmlData = [NSData dataWithContentsOfFile:filePath];
if (htmlData) {
[WebView loadData:htmlData MIMEType:@"text/html" textEncodingName:@"UTF-8" baseURL:baseURL];
}
[self.view addSubview:WebView];
[WebView release];
}
else {
NSLog(@"不存在");
}

[fileManager release];

沒有留言: