一、
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"Stores" ofType:@"html"];
NSURL *dataUrl = [NSURL URLWithString:filePath];
NSString *fileString = [NSString stringWithContentsOfURL:dataUrl
encoding:NSUTF8StringEncoding
error:nil];
int count = 0;
NSScanner *scanner = [NSScanner scannerWithString:fileString];
storeLocations = [[NSMutableArray array] retain];
Locations *location;
NSString *line;
NSArray *values;
while ([scanner isAtEnd] == NO) {
[scanner scanUpToString:@"\n" intoString:&line];
//skip the first line
if(count > 0) {
values = [line componentsSeparatedByString:@","];
location = [[[Locations alloc] init] autorelease];
location.latitude = [[values objectAtIndex:2] floatValue];
location.longitude = [[values objectAtIndex:3] floatValue];
location.magnitude = [[values objectAtIndex:4] floatValue];
location.depth = [[values objectAtIndex:5] floatValue];
[storeLocations addObject:location];
}
count++;
if(count == 15) {
//limit number of events to 15
break;
}
}
二、webView读取本地GBK编码的html
webview打开网页很容易,只有三个方法:
- (void)loadRequest:(NSURLRequest *)request;
- (void)loadHTMLString:(NSString *)string baseURL:(NSURL *)baseURL;
- (void)loadData:(NSData *)data MIMEType:(NSString *)MIMEType textEncodingName:(NSString *)textEncodingName baseURL:(NSURL *)baseURL;
数第一个最容易,只需要一个nsurl地址。什么都不需要你设置。一般万维网的网页都正常,但是我在打开自己的部分网络上的网页还是有乱码。这里没有其它设置,乱码问题除非把网页改成utf-8,不然就需要用到另外两个方法来加载。
我尝试的第三中方法成功的,
首先把数据写到nsdata中
NSData *data = [NSData dataWithContentsOfFile:m_strUrl];
然后设置baseUrl
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0] ; //根据自己的具体情况设置,我的html文件在document目录,链接也是在这个目录上开始
NSURL *baseUrl = [NSURL fileURLWithPath:documentsDir];
为什么需要设置baseUrl?
也就是data中有一些链接是图片,css都是外部文件,然后这些文件需要到一个目录上去找。baseUrl就是这个目录。
最后,使用loadData方法对文件进行加载,并且指定类型(mimetype)和编码类型(textEncodingName)
[self.m_myWebView loadData:data MIMEType:@"text/html" textEncodingName:@"GBK" baseURL:baseUrl];